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

Javascript - Putting ImageData Onto a Canvas Element - CanvasRenderingContext2D

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

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

ctx.putImageData(sourceImage, 0, 0);

这是我当前的 javascript 函数,它接受 img 元素的 class 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 渲染上下文网格时出现错误?

您似乎想要剪切图像的 400x300 部分并将其绘制到 canvas。

您不需要 .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/Whosebug/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/Whosebug/landscape2.jpg">