javascript drawImage(画布)不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10931398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
drawImage (canvas) is not working
提问by Muhammad Usman
I want to draw multiple canvases on a single canvas using drawImage()
method but it is not working
Code
我想使用drawImage()
方法在单个画布上绘制多个画布,但它不起作用
代码
<html>
<head>
<script>
window.onload = function() {
var context1= document.getElementById("canvas1").getContext("2d");
var context2 = document.getElementById("canvas2").getContext("2d");
var context3 = document.getElementById("canvas3").getContext("2d");
context1.font = "20pt Calibri";
context1.fillStyle = "blue";
context1.fillText("Hello ", 50, 25);
context2.font = "20pt Calibri";
context2.fillStyle = "red";
context2.fillText("World!", 100, 25);
var imageObj = new Image();
imageObj.onload = function() {
context3.drawImage(context1.canvas, 50, 25);
context3.drawImage(context2.canvas, 100, 25);
};
};
</script>
</head>
<body>
<canvas id="canvas1" class="canvas" width="200" height="50"></canvas>
<canvas id="canvas2" class="canvas" width="200" height="50"></canvas>
<canvas id="canvas3" class="canvas" width="200" height="50"></canvas>
</body>
</html>?
JS Fiddlehttp://jsfiddle.net/4xT2j/2/
回答by Denys Séguret
Your images have no source. Add one if you want to see something. The onload function cannot be called as long as you don't have a src.
你的图片没有来源。如果你想看什么就加一个。只要您没有 src,就无法调用 onload 函数。
And you must provide the image to the drawImage function :
并且您必须将图像提供给 drawImage 函数:
var imageObj = new Image();
imageObj.onload = function() {
context3.drawImage(imageObj, 50, 25);
context3.drawImage(imageObj, 100, 25);
};
imageObj.src = "someFile.png";
If what you're trying to do is draw canvas1 and canva2 on context3, simply do all this outside the imageObj.onload function which is never called : http://jsfiddle.net/KCyvE/
如果您要做的是在 context3 上绘制 canvas1 和 canva2,只需在从未调用过的 imageObj.onload 函数之外执行所有这些操作:http: //jsfiddle.net/KCyvE/
A precision following a question in comment :
评论中的问题后的精确度:
My code in the fiddle uses context1.canvas
. This works because The context is an instance of CanvasRenderingContext2Dand thus has a property named canvas
which is a "Back-reference to the canvas element for which this context was created".
我在小提琴中的代码使用context1.canvas
. 这工作,因为上下文是一个实例CanvasRenderingContext2D,因而具有命名属性canvas
这是一个“向后引用为其创建此背景下canvas元素”。
回答by bennedich
Your imageObj.onload
function is somewhat wrong. This is what you want: http://jsfiddle.net/4xT2j/3/
你的imageObj.onload
函数有点错误。这就是你想要的:http: //jsfiddle.net/4xT2j/3/
Please observe there isn't necessarily a reason to write canvas3 to an image object since it already is an image object.
请注意,不一定有理由将 canvas3 写入图像对象,因为它已经是图像对象。