Html5 Canvas Pixel Manipulation JavaScript Examples With Code

This example shows you how to use javascript to manipulate Html5 canvas pixels with source code.

1. How To Manipulate Html5 Canvas Pixel In JavaScript Steps.

  1. The Html5 canvas context object’s getImageData(startPointX, startPointY, width, height) method can return all the image pixels in the range specified.
    var imageData = ctx.getImageData(0, 0, img.width, img.height);
  2. The returned ImageData object’s data property is a 2-dimensional list array. The item in the data list is another list that contain the pixel’s RGBA values.
    pixelDataLength = imageData.data.length;
    
    for(var i = 0; i < pixelDataLength; i += 4){
    
        red = imageData.data[i+0];
    
        green = imageData.data[i+1];
       
        blue = imageData.data[i+2];
    
    }
  3. Now you can modify the pixel RGBA as needed, and after that, you can call the context’s putImageData(ImageData, newStartPointX, newStartPointY) to paste the changed pixels to another location.
    ctx.putImageData(imageData, 500, 10);

2. Html5 Canvas Pixel Manipulation Example Source Code.

  1. In this example, you can click the Choose File button to select an image first.
  2. Then click the button Convert Image By Pixel to change the image by pixels.
  3. It will draw both the original image and the converted image on the Html5 canvas, below is the example picture.
    html5-canvas-pixel-manipulation-example
  4. If you meet some error such as Uncaught DOMException DOMException: Failed to execute ‘getImageData’ on ‘CanvasRenderingContext2D’: The canvas has been tainted by cross-origin data. you should browse the example Html file from a local webserver. 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.
  5. This example contains 2 source files, html5-canvas-pixel-manipulation-example.html, html5-canvas-pixel-manipulation-example.js.
  6. html5-canvas-pixel-manipulation-example.html.
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>Html5 Canvas Pixel Manipulation JavaScript Examples With Code</title>
    <script type="text/javascript" src="html5-canvas-pixel-manipulation-example.js" charset="utf-8"></script>
    <style>
    canvas{
      display:block;
      margin-top:10px;
    }
    </style>
    </head>
    <body>
    <h3>Html5 Canvas Pixel Manipulation JavaScript Examples With Code.</h3>
    <div>
        <label>Select Image File:</label>
        <input type="file" id="selectedFile" accept="image/*" style="display:block;margin-top: 10px;"/>
        <div style="display:block;margin-top: 10px;">
            <input type="button" value="Convert Image By Pixel" onclick="convertImageByPixel('canvas1', 'selectedFile')" />
        </div>
        <canvas id="canvas1"></canvas>
    </div>
    </body>
    </html>
  7. html5-canvas-pixel-manipulation-example.js.
    var canvasWidth = 1000;
    var canvasHeight = 800;
    
    //var imgFolderPath = '/Users/songzhao/Documents/WorkSpace/dev2qa.com-example-code/PythonExampleProject/img/';
    var imgFolderPath = '/img/';
    
    function convertImageByPixel(canvasId, fileUploderId){
    
        // Get the html canvas object.
        var canvas = document.getElementById(canvasId);
        
        if(canvas==null){
            alert("Can not find the html canvas element with element id " + canvasId);
            return false;
        }
    
        var fileUploader = document.getElementById(fileUploderId);
        if(fileUploader==null){
            alert("Can not find the html file upload element with element id " + fileUploderId);
            return false;
        }
    
    
        canvas.width = canvasWidth;
        canvas.height = canvasHeight;
        canvas.style.display = 'block';
    
        ctx = canvas.getContext('2d');
    
        ctx.fillStyle = 'rgba(0, 255, 0, 0.5)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    
        fileName = fileUploader.value;
        
        startIndex = fileName.lastIndexOf('\\');
    
        fileName = fileName.substring(startIndex + 1);
    
        img = new Image();
    
        img.src = imgFolderPath + fileName;
    
        //img.crossOrigin = "Anonymous";
    
        img.onload = function(){
    
            ctx.fillStyle = 'blue';
            ctx.font = "36px Arial";
    
            ctx.drawImage(img, 10, 10);
            ctx.fillText("original image", 100, 600);
    
            var imageData = ctx.getImageData(0, 0, img.width, img.height);
    
            pixelDataLength = imageData.data.length;
    
            for(var i = 0; i < pixelDataLength; i += 4){
    
                imageData.data[i+0] = 255 - imageData.data[i+0];
    
                imageData.data[i+1] = 255 - imageData.data[i+2];
    
                imageData.data[i+2] = 255 - imageData.data[i+1];
    
            }
    
            // Paste the changed image pixels to another location to create the converted image.
            ctx.putImageData(imageData, 500, 10);
            ctx.fillText("converted image", 600, 600);
    
        }
    }
0 0 votes
Article Rating
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Clicky
0
Would love your thoughts, please comment.x
()
x