gpt4 book ai didi

javascript - 在 Canvas 上,drawImage 与 png 与使用笔触创建绘图之间的区别?

转载 作者:行者123 更新时间:2023-11-29 18:30:49 32 4
gpt4 key购买 nike

为什么在 Canvas 中处理事物的方式不同?例如,如果我在 Canvas 上放一个 png vs 在 Canvas 上画一条线。当我将该 Canvas 的内容复制到另一个 Canvas 时,只会复制该行。

var thecanvas = document.getElementById('mycanvas');
var context = thecanvas.getContext('2d');

// put a png on the canvas
var img = new Image();
img.onload = function(){ context.drawImage(img,0,0); };
img.src = 'images/test.png';

// draw a line on the canvas
context.moveTo(100, 150); context.lineTo(450, 50); context.stroke();

final_image = thecanvas.toDataURL("image/png");
copyimg = new Image();
copyimg.src = final_image;
var newcanvas = document.getElementById('newCanvas');
var newcanvascontext = newcanvas.getContext('2d');

// why is only the line I drew copied over and not the png image???
newcanvascontext.drawImage(copyimg,0,0,397,397);

最佳答案

请注意图像加载事件。在加载图像之前复制 Canvas 。你必须这样做

var thecanvas = document.getElementById('mycanvas');
var context = thecanvas.getContext('2d');

// put a png on the canvas
var img = new Image();
img.onload = function(){

context.drawImage(img,0,0);

var newcanvas = document.getElementById('newCanvas');
var newcanvascontext = newcanvas.getContext('2d');
newcanvascontext.drawImage(thecanvas,0 ,0);

};
img.src = 'http://www.mygreatiphone.com/wp-content/uploads/2011/11/google.png';

// draw a line on the canvas
context.moveTo(100, 150); context.lineTo(450, 50); context.stroke();

查看演示:http://jsfiddle.net/diode/3NHXy/5/

关于javascript - 在 Canvas 上,drawImage 与 png 与使用笔触创建绘图之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8600438/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com