开发者

HTMLCanvasContext.drawImage() failing when passed an image found using jQuery

The idea of my code is create a hidden div which loads the image. When it's load event is fired draw it in the canvas. When I run the code I get this error 0x80040111 (NS_ERROR_NOT_AVAILABLE), yet I am waiting for the load event. Here is my code.

HTML

<div id="old-counties-image-wrapper" style="display: none;">
<img border="0" height="390" id="interreg-iiia-old-counties-map" src="/f/MISCELLANEOUS/old-map.jpg" /></div>
<p>
<canvas id="old-counties-image-canvas"></canvas></p>

and javascript

 $('#interreg-iiia-old-counties-map').load(function() {
    var canvas=document.getElementById('old-counties-image-canvas');
    if (canvas.getContext) {
         var ctx=canvas.getContext('2d');
         var img=$('#interreg-iiia-old-counties-map');
         ctx.drawImage(img, 0, 0);
    }
    //else {
    //    $('#old-counties-image-wrapper').show();
    //}
   });

The else part is commented out for now but is there for browsers that d开发者_如何学运维on't support canvas.


Because $('#interreg-iiia-old-counties-map') returns a jQuery object, while the drawImage method takes an Image object - the jQuery ($) function returns a jQuery object that wraps the original element to provide the usual jQuery functions you see.

You can get the underlying Image object by using the get method, but in this case it would be easier to just use this, which in the context of the callback function supplied to the load function, is the original $('#interreg-iiia-old-counties-map') DOM element. In other words,

ctx.drawImage(this, 0, 0);

should work fine here. You also don't have to use a hidden <img> element - with new Image you can retrieve the image similar to what you're doing here:

var img = new Image(), 
    canvas = document.getElementById('old-counties-image-canvas');
img.src = '/f/MISCELLANEOUS/old-map.jpg';

img.onload = function(){
    if (canvas.getContext) {
         var ctx = canvas.getContext('2d');
         ctx.drawImage(img, 0, 0);
    }
};


And, now for my own take on a solution:

var imgId = $("#myDiv img").attr("id");
var imgObj = document.getElementById(imgId);
var canvasContext = $("#imgCanvas")[0].getContext('2d');
canvasContext.drawImage(imgObj, 0, 0);

It's ugly, but I don't think it's much uglier than the solutions presented above. There may be performance advantages to other solutions as well, though this one seems to avoid needing to load the image file from the server's file system, which should be worth something. I tested it in Chrome, Firefox, and IE10.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜