我在向另一个画布显示一个画布时遇到问题。我根据this solution
做了一切<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>
好吧,第一个canvas元素正确显示图片,但无论我做什么,第二个画布都不想显示图片。
答案 0 :(得分:0)
您正在尝试在加载图像之前从源绘制图像,并且源甚至还有图像。
在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';
答案 1 :(得分:0)
<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
之前尝试访问canvas元素答案 2 :(得分:0)
您目前构建代码的方式,img.onload在 destin_ctx.drawImage行之后执行。这意味着您的程序流程目前看起来像这样:
您需要做的是将destin_ctw.drawImage调用移动到执行流程中的某个位置,您知道源画布肯定会包含相应的内容。在这个简单的例子中,将它移动到图像的onload内部就可以了。
这是一个完整的(但简化的)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>