How To Pixel An Image Using Html5 Canvas

This article will tell you how to draw a pixel style of an image using Html5 canvas with examples.

1. How To Pixel An Image Using Html5 Canvas Example.

  1. There are 1 file selector and 2 buttons in this example.
  2. First, you should choose the image file by the file selector.
  3. Click the Draw Original Image button will draw the original image on the left.
  4. Then click the Draw Pixel Image button to draw the pixel style of the original image.
  5. When you click the Draw Pixel Image button, it will first get and save the original image’s single-pixel coordinate & color information for every size-number pixel apart to an array object, you can change the size-number to an integer number to adjust the pixel effect.
  6. Then you should loop the above single-pixel array, and draw the pixel color to a square with the size-number width and height to see the pixel style image.
  7. This example contains 2 source files, how-to-pixel-an-image-using-html5-canvas.html, how-to-pixel-an-image-using-html5-canvas.js.
  8. how-to-pixel-an-image-using-html5-canvas.html.

    <!DOCTYPE html>
    <meta charset="ISO-8859-1">
    <title>How To Pixel An Image Using Html5 Canvas</title>
    <script type="text/javascript" src="how-to-pixel-an-image-using-html5-canvas.js" charset="utf-8"></script>
    <h3>How To Pixel An Image Using Html5 Canvas.</h3>
        <div style="display:block">
            <label>Select Image File:</label>
            <input type="file" id="imageFile" accept=".jpeg,.jpg,.png" />
        <div style="display:block; margin-top: 10px;"></div>
            <input type="button" id="drawOriginalImage" value="Draw Original Image" onclick="drawOriginalImage('originalImageCanvas', 'imageFile')" />
            <input type="button" id="drawPixelImage" value="Draw Pixel Image" onclick="drawPixelImage('originalImageCanvas', 'pixelImageCanvas')" />
        <canvas id="originalImageCanvas"></canvas>
        <canvas id="pixelImageCanvas"></canvas>
  9. how-to-pixel-an-image-using-html5-canvas.js.
    var canvasWidth = 300;
    var canvasHeight = 300;
    //var imgFolderPath = '/Users/songzhao/Documents/WorkSpace/';
    //var imgFolderPath = 'D:/Work/';
    var imgFolderPath = '/img/';
    function drawOriginalImage(canvasId, fileUploderId){
        // Get the html canvas object.
        var canvas = document.getElementById(canvasId);
            alert("Can not find the html canvas element with element id " + canvasId);
            return false;
        var fileUploader = document.getElementById(fileUploderId);
            alert("Can not find the html file upload element with element id " + fileUploderId);
            return false;
        canvas.width = canvasWidth;
        canvas.height = canvasHeight;
        // = 'block'; = 'green';
        ctx = canvas.getContext('2d');
        fileName = fileUploader.value;
        startIndex = fileName.lastIndexOf('\\');
        fileName = fileName.substring(startIndex + 1);
        img = new Image();
        img.src = imgFolderPath + fileName;
        img.onload = function(){
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);      
    function drawPixelImage(originalCanvasId, pixelCanvasId){
        // Get the html canvas object that draw the original image.
        var originalCanvas = document.getElementById(originalCanvasId);
            alert("Can not find the html canvas element with element id " + originalCanvasId);
            return false;
        // Get the html canvas object that draw the pixel image.
        var pixelCanvas = document.getElementById(pixelCanvasId);
            alert("Can not find the html canvas element with element id " + pixelCanvasId);
            return false;
        originalCtx = originalCanvas.getContext('2d');
        // Define the pixel width that means how may pixel will use the same color.
        pixelSize = 10;
        // Define the pixel array to save the selected pixel coordinates and color.
        // Each pixel item data is an object of {x:, y:, color}.
        let pxObjectArray = [];
        // Loop in the original canvas, get single pixel color every pixelSize distance.
        for (let i = 0; i < originalCanvas.width; i += pixelSize) {
            for (let j = 0; j < originalCanvas.height; j += pixelSize) {
                // Get the single pixel information from the original image. 
                let pixel = originalCtx.getImageData(i, j, 1, 1).data;
                // Create the color object from the single pixel.
                let color = `rgba(${pixel[0]},${pixel[1]},${pixel[2]},${pixel[3]/255})`;
                //let color = 'rgba('+ pixel[0] + ',' + pixel[1] + ',' + pixel[2] +',' + pixel[3] +')';
                console.log('color = ' + color);
                // Push the pixel object ( contains x, y coordinates and color ) to the pixel array. 
                pxObjectArray.push({ x: i / pixelSize, y: j / pixelSize, color });
        // Set the pixel canvas width, height, background color.
        pixelCanvas.width = originalCanvas.width;
        pixelCanvas.height = originalCanvas.height; = 'red';
        // Get the pixel canvas's context object. 
        pixelCtx = pixelCanvas.getContext('2d');
        // Loop in the pxObjectArray object.
        var pxObjectArraySize = pxObjectArray.length;
        for(var i=0; i<pxObjectArraySize; i++)
            pxObject = pxObjectArray[i];
        //pxObjectArray.forEach((pxObject) => {
            const { color, x, y } = pxObject;
            pixelCtx.fillStyle = color;
            pixelCtx.fillRect(x*pixelSize, y*pixelSize, pixelSize, pixelSize);
  10. If you meet an error such as Uncaught DOMException DOMException: Failed to execute ‘getImageData’ on ‘CanvasRenderingContext2D’: The canvas has been tainted by cross-origin data when you run the above example by browsing the local file in a web browser, you can read the article How To Fix Error Access To Script At From Origin ‘null’ Has Been Blocked By Cors Policy: Cross Origin Requests Are Only Supported For Protocol Schemes: Http, Data, Chrome, Chrome-extension, Chrome-untrusted, Https.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.