1

我有以下代码:

var img = new Image();
canvas = document.getElementById("c");
ctx = canvas.getContext('2d')
canvas2 = document.getElementById("c2");
ctx2 = canvas2.getContext('2d')
img.onload = function () {
    canvas.width = img.width;
    canvas.height = img.height;
ctx.drawImage(img,0,0);
};
img.src = 'mwq.gif';
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
ctx2.putImageData(imageData, 0, 0);

我在第一个画布元素上获取图像,当我在控制台中签入时,有 imageData,具有宽度、长度和像素数组,但不知何故我无法在另一个画布元素上获取该图像。我不认为有错别字,我多次重写相同的代码,最后我将它剥离到没有像素操作的最小版本,但它仍然无法正常工作。

4

1 回答 1

2

Your code isn't called in the onload callback, it's executed before the image is loaded so there is nothing to put.

You could change it to

var img = new Image();
canvas = document.getElementById("c");
ctx = canvas.getContext('2d')
canvas2 = document.getElementById("c2");
ctx2 = canvas2.getContext('2d')
img.onload = function () {
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img,0,0);
    var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    ctx2.putImageData(imageData, 0, 0);
};
img.src = 'mwq.gif';
于 2012-08-24T10:47:07.680 回答