sneaky
sneaky

Reputation: 2201

How to load img src from another domain for canvas?

When I load an image in my canvas and specify its src I use a file name that's in the same folder as the html file, and that loads the img. So it would be like this:

img.src = 'Untitled.png'; 

But if I try this, the img doesn't load

img.src = 'http://dgroover.wikispaces.com/file/view/bill-gates-car.jpg'; 

Does anyone know whats wrong?

Upvotes: 0

Views: 3349

Answers (2)

Jeetu
Jeetu

Reputation: 156

Try out in this way :

> var canvas = document.getElementById("myCanvas");
>         var ctx = canvas.getContext("2d");      
>         ctx.translate(0.5, 0.5);
>         ctx.strokeStyle = "#5F7FA2";
>         ctx.strokeRect(50, 50, 25, 25);
>         var img = new Image();
>         img.src = "http://www.cs.washington.edu/education/courses/csep576/05wi/projects/project4/web/artifact/liebling/average_face.gif";
>         img.onload = function(){
>         ctx.drawImage(img, 50, 50);}

Upvotes: 0

Engineer
Engineer

Reputation: 48793

Works with this code:

markup part

<canvas id="cnv" width="500" height="500"></canvas>

script part

var img = new Image();
img.onload = function(){
    document.getElementById("cnv").getContext("2d").drawImage(this,0,0);
};
img.src="http://dgroover.wikispaces.com/file/view/bill-gates-car.jpg";​

DEMO

Upvotes: 1

Related Questions