我在使用safari / mobile safari进行图像加载和触发时出现问题。我有一个在画布上绘制的自定义对象,但需要等到对象图像属性已加载,因为它在绘制时使用图像的尺寸。以下代码在ff上工作正常,但在safari中失败:
function canvasSlider(){
this.slideImg=new Image();
this.slideImg.src="images/back_button.png";
this.somevalue=55;
}
canvasSlider.prototype.init = function (){
alert(this.slideImg.complete + ', ' + this.slideImg.height+', ' + this.somevalue);
}
var myObj = new canvasSlider();
myObj.init();
在safari中,对于this.slideImg.complete
,它总是返回false我如何使用this.slideImg.onload = somefunction();并始终确保传递canvasSlider对象?
function canvasSlider(){
this.slideImg=new Image();
this.slideImg.onload=somefunction(this);
this.slideImg.src="images/back_button.png";
this.somevalue=55;
}
function somefunction(obj){
alert(obj.slideImg.complete+', '+obj.slideImg.src);
}
var myObj = new canvasSlider()
这不起作用。有任何想法吗? 感谢
答案 0 :(得分:3)
图像异步加载,因此您必须在成功加载图像时触发绘图操作。你在onload的正确道路上。你可以这样做:
function canvasSlider(readyFunc){
var self = this;
this.slideImg=new Image();
this.slideImg.onload = function() {
self.init();
if (readyFunc) {
readyFunc.call(self);
}
};
this.somevalue=55;
// The last thing you should do in the constructor is set the .src value
// That's because if the image is in the cache, some browsers will trigger
// onload immediately when you set .src and we want the canvasSlider object
// to be fully formed when init() and readyFunc() are called.
this.slideImg.src="images/back_button.png";
}
canvasSlider.prototype.init = function (){
alert(this.slideImg.complete + ', ' + this.slideImg.height+', ' + this.somevalue);
}
var myObj = new canvasSlider(function() {
// The slider is ready with the image loaded here
// and .init() has already been called.
// "this" right here is the canvasSlider object
// you can do anything else you wanted to do once the image was loaded
});
// The image is not necessarily loaded here.
// You have to put anything that relies on the image being loaded in the
// above callback to assure it is not executed until the image is loaded.
注意:在测试代码时,如果图像位于浏览器缓存中,某些浏览器会立即触发onload。您应该测试两种方式(使用浏览器缓存中的图像而不使用浏览器缓存中的图像)以确保两种情况都正常工作。开发人员通常认为一切正常(因为图像在浏览器缓存中),然后它对下一个尝试它的用户不起作用。