Javascript - 将ImageData放到Canvas元素上 - CanvasRenderingContext2D

时间:2015-01-30 04:28:42

标签: javascript canvas

我想获取一个源图像,并将其像素数据放入一个带有CanvasRenderingContext2D网格的元素中。

我正在编写一个javascript函数来处理某些像素点的数据, 但我不断从这一行得到错误:

ctx.putImageData(sourceImage, 0, 0);

这是我当前的javascript函数,它接受img元素的类ID作为其参数:

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);
}

当我尝试将源图像的像素数据放入2D渲染上下文网格时,为什么会出现错误?

1 个答案:

答案 0 :(得分:0)

看起来您想要剪切图像的400x300子部分并将其绘制到画布中。

您无需.getImageData.putImageData即可完成此任务。

您可以使用.drawImage的剪辑版本来执行此操作:

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)
)

这是示例代码和演示:

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">