【问题标题】:javascript custom object and image onloadjavascript自定义对象和图像加载
【发布时间】:2012-02-01 08:17:51
【问题描述】:

我在使用 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()

这不起作用。有任何想法吗? 谢谢

【问题讨论】:

  • 您可以尝试使用 jquery 或 YUI 进行事件处理,我知道它们可以为自定义事件对象提供支持。
  • 嗨,杰夫,我还没有使用 jquery。我想但不想重写。谢谢

标签: javascript image object onload


【解决方案1】:

图片加载是异步的,所以你必须在图片加载成功后触发绘图操作。你在 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。您应该测试两种方式(使用浏览器缓存中的图像和没有浏览器缓存中的图像)以确保两种情况都正常工作。开发人员通常认为一切正常(因为图像在他们的浏览器缓存中),然后对于下一个尝试它的用户就不起作用了。

【讨论】:

  • 哇,真快!谢谢,是的,它确实有效。就这样我掌握了它,if (readyFunc) 语句将执行新 canvasSlider 声明中的代码?
  • @stevo - 是的,你说得对。 canvasSlider 的 readyFunc 参数是可选的。它允许您指定将在图像加载并可用时立即执行的代码。
猜你喜欢
  • 2014-07-07
  • 2013-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-20
  • 2020-06-07
  • 1970-01-01
相关资源
最近更新 更多