我认为我遇到了与 this question 类似的问题,但我需要一些帮助来了解如何使用回调函数以及如何针对我的特定情况实现它。我试图“按需”将图像绘制到 Canvas 上,即任何时候调用某个函数时。该图像与一个我称为“ block ”的对象相关联。 block 具有尺寸、坐标和 url。
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之前,并且我需要使用回调或promise来解决这个问题,但我对Javascript很陌生,所以我想在这里得到一些指导。任何帮助或建议将不胜感激。
最佳答案
尝试这样:
function Block(x, y, width, height, url) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.url = url;
this.drawBlock=function drawBlock(){
var blockSprite = new Image();
blockSprite.src = url;
blockSprite.onload = function(){
context.drawImage(blockSprite,x,y,width,height);
}
}
}
var block=new Block(0,0,32,32,"house32x32.png");
block.drawBlock();
回调只是一个稍后执行的函数——通常是在长时间运行的任务最终完成之后。
加载图像就是一个很好的例子。考虑这段代码:
function someCallbackFunction(){
alert("The image has finally been fully loaded");
}
var image=new Image();
image.onload=someCallbackFunction;
image.src="yourImage.png";
alert("This code is last, but will execute before the onload function");
它实际上会按以下顺序执行:
图像对象已创建。
var image=new Image();
图像对象被告知,当它完全加载图像后,它应该执行名为 someCallbackFunction 的函数。
image.onload=someCallbackFunction
图像被赋予一个 .src URL 并开始下载图像的漫长过程
image.src="yourImage.png";
image.src="yourImage.png"之后的任何代码都将执行。
...稍后...图像完全加载后,图像对象将执行 someCallbackFunction() 并且警报将响起。
关于Javascript 使用回调将图像绘制到 Canvas 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21654114/