Search code examples
javascriptcanvas

Javascript - Putting ImageData Onto a Canvas Element - CanvasRenderingContext2D


I want to take a source image and put its pixel data into a element with a CanvasRenderingContext2D grid.

I'm writing a javascript function to work with certain pixel points of data, but I keep getting an error from this line:

ctx.putImageData(sourceImage, 0, 0);

Here is my current javascript function that accepts a class ID of an img element as its argument:

function mapMyImage(sourceImageID) {

    // Declare variable for my source image
    var sourceImage = document.getElementById(sourceImageID);

    // Creates a canvas element in the HTML to hold the pixels
    var canvas = document.createElement('canvas');

    // Create a 2D rendering context for our canvas
    var ctx = canvas.getContext('2d');

    // After the image has loaded, put the source image data into the
    // 2D rendering context grid
    function imgToPixelArray() {
    // In the context of the canvas, make an array of pixels
    ctx.putImageData(sourceImage, 0, 0);
    }

    // Call the above function once the source image has loaded
    sourceImage.onload = imgToPixelArray();

    // Get Access to the pixel map now stored in our 2D render
    var imageData = ctx.getImageData(0, 0, 400, 300);
}

Why am I getting an error when I am trying to put my source image's pixel data into a 2D rendering context grid?


Solution

  • It looks like you want to clip a 400x300 subsection of the image and draw it into the canvas.

    You don't need .getImageData and .putImageData to accomplish that.

    You can use the clipping version of .drawImage to do that:

    context.drawImage(
        img,              // the image source
        0,0,              // start clipping from the source at x=0, y=0
        400,300           // clip a subsection that's 400x300 in size
        0,0               // draw that clipped subsection on the canvas at x=0,y=0
        400,300           // make the drawing 400x300 (don't scale)
    )
    

    Here's example code and a Demo:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    
    
    var img=new Image();
    img.onload=start;
    img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/landscape2.jpg";
    function start(){
      ctx.drawImage(img, 0,0,400,300, 0,0,400,300);
    }
    body{ background-color: ivory; padding:10px; }
    #canvas{border:1px solid red;}
    <h4>subsection clipped to the canvas</h4>
    <canvas id="canvas" width=400 height=300></canvas>
    <h4>The original image</h4>
    <img src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/landscape2.jpg">