admin管理员组

文章数量:1391989

I am trying to load a picture into HTML5 Canvas. when i use a URL to load the image everything works fine, but if i put the image on the local drive and point to it, nothing happens.

note: when i use a regular tag, everything works fine and the image is loaded.

here is the code:

  var canvas = document.getElementById("rightSide");
    var context = canvas.getContext("2d");
    var imageObj = new Image();
    imageObj.src = "cloud.gif";
    context.drawImage(imageObj, 650, 55, 93, 104);

< canvas id="rightSide" width="800px" height="800">

thanks.

I am trying to load a picture into HTML5 Canvas. when i use a URL to load the image everything works fine, but if i put the image on the local drive and point to it, nothing happens.

note: when i use a regular tag, everything works fine and the image is loaded.

here is the code:

  var canvas = document.getElementById("rightSide");
    var context = canvas.getContext("2d");
    var imageObj = new Image();
    imageObj.src = "cloud.gif";
    context.drawImage(imageObj, 650, 55, 93, 104);

< canvas id="rightSide" width="800px" height="800">

thanks.

Share asked May 21, 2012 at 11:23 GleebGleeb 11.3k28 gold badges96 silver badges139 bronze badges 1
  • When is the code being executed? In a script tag, or onload, or what? – Phil H Commented May 21, 2012 at 11:34
Add a ment  | 

2 Answers 2

Reset to default 9

Try something like this.

<canvas id="canvas"></canvas>

var can = document.getElementById('canvas');
var ctx = can.getContext('2d');

var img = new Image();
img.onload = function(){
    can.width = img.width;
    can.height = img.height;
    ctx.drawImage(img, 0, 0, img.width, img.height);
}
img.src = 'image.jpg';

A local file being loaded into canvas is treated as being from a different source and therefore "tainted". This is why it's not working for your local file, but does for a URL.

本文标签: javascripthtml5 image is not loaded into canvasStack Overflow