简体   繁体   English

Javascript:我无法在画布上绘制图像

[英]Javascript: I cannot draw image on the canvas

I already create my canvas on my page, however when I try to import an image on the canvas, it does not appear, here are the code I used. 我已经在页面上创建了画布,但是当我尝试在画布上导入图像时,它没有出现,这是我使用的代码。 (the makeGameArea is a method I created to make a canvas on the webpage, the code of this method is not shown because it is so long to put it here) (makeGameArea是我创建的用于在网页上制作画布的方法,该方法的代码未显示,因为将其放置在此处太长了)

Here are the following code that should have problem 以下是应该有问题的以下代码

var myGameArea2 = makeGameArea(700, 150, "myArea", "white");
var myContext2 = myGameArea2.getContext("2d");

var myImage = new drawImage(myContext2, "sonic.gif", 91, 97, 0, 0);
myImage.draw();

function drawImage(ctx, src, width, height, x, y){
     this.image = new Image();
     this.image.src = src;
     this.width = width;
     this.height = height;
     this.x = x;
     this.y = y;
     this.draw = function(){
         this.image.onload = function(){                  
             ctx.drawImage(this.image, this.x, this.y, this.width, this.height); 
         }
     }           

} }

Is there anything wrong with my drawImage() method? 我的drawImage()方法有什么问题吗?

HTMLImage. HTMLImage。 onload will fire only once per src setting. 每个src设置onload只会触发一次。

Here you are attaching your handler in the draw method, which I guess will be called later on. 在这里,您将您的处理程序附加到draw方法中,我猜稍后会调用它。 At this moment, the event will already have fired, and hence will never be called, since it won't fire again unless you reset its src . 此时,该事件将已经触发,因此将不会被调用,因为除非您重置其src否则它将不会再次触发。

Fixed code block: 固定代码块:

function drawImage(ctx, src, width, height, x, y){
     this.image = new Image();
     this.width = width;
     this.height = height;
     this.x = x;
     this.y = y;
     this.draw = function(){
        ctx.drawImage(this.image, this.x, this.y, this.width, this.height));
        };
     // if you want it to draw as soon as possible
     this.image.onload = this.draw.bind(this);
     this.image.src = src;
     }

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

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