虚拟画布概念的新手,任何想法为什么下面的代码不起作用?
<script type="text/javascript">
$(document).ready(function () {
var c1 = document.createElement('canvas');
var ctx1 = c1.getContext("2d");
var c2 = document.getElementById('Canvas2');
var ctx2 = c2.getContext("2d");
c1.width = c2.width;
c1.height = c2.height;
img1 = new Image();
img1.src = 'A1.png';
img1.onload = function () {
ctx1.drawImage(this, 0, 0);
};
imgdata = ctx1.getImageData(0, 0, c2.width, c2.height);
ctx2.putImageData(imgdata, 0, 0);
});
</script>
<canvas id="Canvas2" style="display:block;position:absolute;background-color:transparent;border:1px solid red;">
Your browser does not support the HTML5 canvas tag.
</canvas>
如果我绘制矩形或任何其他对象,但是当我加载图像时,该概念有效 不显示虚拟画布上加载的图像。如下例所示可以正常工作。
$(document).ready(function () {
var c1 = document.createElement('canvas');
var ctx1 = c1.getContext("2d");
var c2 = document.getElementById('Canvas2');
var ctx2 = c2.getContext("2d");
c1.width = c2.width;
c1.height = c2.height;
ctx1.fillRect(0, 20, 20, 20);
imgdata = ctx1.getImageData(0, 0, c2.width, c2.height);
ctx2.putImageData(imgdata, 0, 0);
});
答案 0 :(得分:1)
你必须等待getImageData等直到图像加载完毕,所以在图像加载到onload处理程序中之后移动需要完成的所有操作(或者将它们包装在一个调用的函数中)的onload):
img1.onload = function () {
ctx1.drawImage(this, 0, 0);
imgdata = ctx1.getImageData(0, 0, c2.width, c2.height);
ctx2.putImageData(imgdata, 0, 0);
};
如果你不这样做,那么当你调用getImageData导致空白字节数组时,图像可能无法加载并绘制到画布上。