Iam Noobiesh
Iam Noobiesh

Reputation: 91

Export Canvas WITH an image AS an image (like PNG or jpg)

I just basically want to get the "http://... .png" or "http://... .jpg" location of my canvas as an image.

I have already tried toDataURL() but it is not working. Especially if I loaded an image within the canvas.

Here is my code: (btw, I'm using jQuery here)

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
 var canvas = $("#canvas");
 var ctx = canvas.get(0).getContext("2d");

 var image1 = new Image();
 image1.src = "http://www.helpinghomelesscats.com/images/cat1.jpg"
 $(image1).load(function(){
   ctx.drawImage(image1,0,0,200,200);
 });

});
</script>

with my html/body having only this:

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

now, if you try that, that works fine. it shows that cat.

but when i add that toDataURL into my script, it just doesn't happen.

var dataImg = canvas.get(0).toDataURL();

i load this dataImg variable into another click-redirect function to test it, hoping it would redirect to the page using the base64 url it contains, but it just doesn't work:

$("#canvas").click(function(){
  document.location = dataImg;
});

it brings me to a blank page? what am i missing here?

thank you very much!

Upvotes: 1

Views: 1947

Answers (1)

Loktar
Loktar

Reputation: 35319

Do you own http://www.helpinghomelesscats.com or is your code hosted directly on that site? If not you won't be able to do this due to cross site origin policies. The best way would be to have some server side code grab the image and then serve it locally on your domain.

If you do own helpinghomelesscats.com this should work, as tested here

Live Demo

Click the canvas and view the log in order to see the response.

Upvotes: 1

Related Questions