我想我有一个类似的问题,this question,但我想了解如何使用回调函数,以及如何实现它为我的特定情况一点帮助。我试图让图像按需“绘制到画布上,即任何时候调用某个函数。图像与我称之为块的对象相关联。块有尺寸,坐标和网址。Javascript使用回调画一个图像到画布
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
function Block(x, y, width, height, url) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.url = url;
this.drawBlock = drawBlock;
function drawBlock() {
var blockSprite = new Image();
blockSprite.src = url;
blockSprite.onload = context.drawImage(blockSprite,x,y,width,height);
}
}
您可以看到演示here。奇怪的是,如果我链接到网络上的图像,它会工作,但如果我链接到我的磁盘上的图像失败。我相信这是因为onload事件发生在drawBlock被调用之前,而且我需要使用回调函数或承诺来解决这个问题,但我对Javascript很陌生,所以我想在这里稍微介绍一下。任何帮助或建议,将不胜感激。
尝试用'的window.onload =函数周围代码(){};' – James
@JamesBrown其实,我已经有我周围的所有代码。一旦他们准备好了,我就会将一些东西绘制到画布上,而且它的一部分工作正常。 – Era