[英]how to remove one canvas element from displaying on top of another canvas element
[英]Displaying one canvas to another
将一个画布显示到另一个画布时出现问题。 我根据这个解决方案做所有事情
<script>
var source = document.getElementById('hiddenCanvas');
var source_ctx = source.getContext('2d');
var img = new Image();
img.onload = function(){
source.width = img.width;
source.height = img.height;
source_ctx.drawImage(img, 0, 0, img.width, img.height);
}
img.src = 'icon.jpg';
var destination = document.getElementById('visibleCanvas');
var destin_ctx = destination.getContext('2d');
destin_ctx.drawImage(source, 0, 0);
</script>
好吧,第一个画布元素正确显示图片,但是无论我做什么,第二个画布都不想显示图片。
您正在尝试从图像源中加载图像,然后再加载图像甚至源图像。
将最后一个绘制操作onload
处理程序中。 还记得设置目标画布的大小:
var source = document.getElementById('hiddenCanvas');
var source_ctx = source.getContext('2d');
var destination = document.getElementById('visibleCanvas');
var destin_ctx = destination.getContext('2d');
var img = new Image();
img.onload = function(){
source.width = img.width;
source.height = img.height;
source_ctx.drawImage(img, 0, 0, img.width, img.height);
destination.width = source.width;
destination.height = source.height;
destin_ctx.drawImage(source, 0, 0);
}
img.src = 'icon.jpg';
<script>
function init()
{
var source = document.getElementById('hiddenCanvas');
var source_ctx = source.getContext('2d');
var destination = document.getElementById('visibleCanvas');
var destin_ctx = destination.getContext('2d');
var img = new Image();
img.onload = function(){
source.width = img.width;
source.height = img.height;
source_ctx.drawImage(img, 0, 0, img.width, img.height);
destin_ctx.drawImage(source, 0, 0);
}
img.src = 'arun.jpg';
}
</script>
</head>
<body onload="init();">
<canvas id="hiddenCanvas" />
<canvas id="visibleCanvas" />
您的代码无法正常工作,因为您尝试在将画布元素加载到dom之前对其进行访问
当前构建代码的方式img.onload在destin_ctx.drawImage行之后执行。 这意味着您的程序流当前看起来像这样:
您需要做的是将destin_ctw.drawImage调用移到执行流中的某个位置,您知道源画布肯定包含适当的内容。 在这种简单情况下,将其移动到图像的内部加载即可。
这是一个完整(但经过简化)的HTML文件,该文件在Chromium中对我有用,但图像网址已更改:
<script> function load() { var source = document.getElementById('hiddenCanvas'); var source_ctx = source.getContext('2d'); var destination = document.getElementById('visibleCanvas'); var destin_ctx = destination.getContext('2d'); var img = new Image(); img.onload = function(){ source.width = img.width; source.height = img.height; source_ctx.drawImage(img, 0, 0, img.width, img.height); destin_ctx.drawImage(source, 0, 0); } img.src = 'ship360_32.png'; } </script> <body onload="load()"> <canvas id="hiddenCanvas"></canvas> <canvas id="visibleCanvas"></canvas> </body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.