尝试通过画布绘制图像时出现异常

时间:2011-04-17 23:42:48

标签: javascript html canvas

我正在尝试绘制我从Flickr通过画布获取的图片,这是我的代码片段。

for(var i=0;i<document.getElementsByClassName("canvas").length;++i)
            {
                //randomly select one photo
                var picinfo = photos[Math.floor(Math.random()*photos.length)];
                var img = new Image(); 
                //get the pic URL
                img.src = "http://farm" + picinfo.farm + ".static.flickr.com/"
                + picinfo.server + "/" + picinfo.id + "_" + picinfo.secret + "_m.jpg";

                var ctx = document.getElementsByClassName("canvas")[i].getContext('2d');

                console.log(img);

                // Draw slice
                ctx.drawImage(img, 10, 10);
                // Draw frame
                //ctx.drawImage(document.getElementById('frame'),132,150);
            }

直到实际绘制图片

才有效
ctx.drawImage(img, 10, 10);

它引发了我不知道的异常。

uncaught exception: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIDOMCanvasRenderingContext2D.drawImage]" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: http://localhost:8080/static/js/Gallery.js :: anonymous :: line 25" data: no]

我猜图像提取没有任何问题,因为我可以在我的Firebug中看到提取的图片

<img src="http://farm6.static.flickr.com/5226/5624531777_4a05934fc1_m.jpg">

并且有帮助吗?提前谢谢你。

1 个答案:

答案 0 :(得分:0)

根据您的有限信息,很难为您测试任何内容或重复您的错误,但我认为我可以提供帮助。

NS_ERROR_NOT_AVAILABLE可能是因为试图过快地拨打太多电话,但我不太确定。

即使不是,我们也可以通过重新安排您的代码来认真解决这个问题。我们将获取一张图像,等待它加载,绘制该图像,然后转到下一张图像,而不是快速浏览每张图像。

我已在下面重新安排了您的代码,但尚未对其进行测试 - 您必须这样做! - 因为我没有你所做的所有作品。

这不一定是解决问题的最佳方式,但正如所写,它应该有效

function drawOne(i) {
  //randomly select one photo
  var picinfo = photos[Math.floor(Math.random()*photos.length)];
  var img = new Image(); 
  //get the pic URL
  img.src = "http://farm" + picinfo.farm + ".static.flickr.com/"
  + picinfo.server + "/" + picinfo.id + "_" + picinfo.secret + "_m.jpg";

  // When the image is done loading this will execute
  img.onload = function() {
    var ctx = document.getElementsByClassName("canvas")[i].getContext('2d');

    console.log(img);

    // Draw slice
    ctx.drawImage(img, 10, 10);
    // Draw frame
    //ctx.drawImage(document.getElementById('frame'),132,150);

    // we're done with this image? call drawOne again!
    // We may have to wait for a second here... but maybe not.
    i++;
    if (i !== document.getElementsByClassName("canvas").length) {
      drawOne(i);
    }
  }
}

// Get things started
drawOne(0);
相关问题