我有以下代码:
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);
并且我在第一个canvas元素上获得图像,当我在控制台中检查时有imageData,有宽度,长度和像素数组,但不知怎的,我无法在另一个canvas元素上获得该图像。我不认为有拼写错误,我多次重写相同的代码,最后我把它剥离到最小的版本没有像素操作,但它仍然无法正常工作。
答案 0 :(得分:2)
您的代码未在onload
回调中调用,它在图像加载之前执行,因此无需放置任何内容。
您可以将其更改为
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';