我想我有一个类似的问题到了这个问题,但我想一点点帮助了解如何使用一个回调函数,以及如何实现它为我的特殊情况。我正在尝试“按需”将图像绘制到画布上,即每次调用某个函数时。该图像与我称为“块”的对象相关联。块具有尺寸,坐标和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);
}
}
您可以在此处查看演示。奇怪的是,如果我链接到网络上的图像,它就可以工作,但是如果我链接到磁盘上的图像,它就不能工作。我相信这是因为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()并发出警报。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句