简体   繁体   English

drawImage(画布)不起作用

[英]drawImage (canvas) is not working

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 Fiddle http://jsfiddle.net/4xT2j/2/ JS小提琴 http://jsfiddle.net/4xT2j/2/

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 . 我在小提琴中的代码使用context1.canvas This works because The context is an instance of CanvasRenderingContext2D and thus has a property named canvas which is a "Back-reference to the canvas element for which this context was created" . 这是可行的 ,因为上下文是CanvasRenderingContext2D的实例,因此具有名为canvas的属性,该属性是“对创建此上下文的canvas元素的反向引用”

Your imageObj.onload function is somewhat wrong. 您的imageObj.onload函数有些错误。 This is what you want: http://jsfiddle.net/4xT2j/3/ 这就是您想要的: 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写入图像对象,因为它已经是图像对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM