PHP / Javascript / HTML5 canvas - loading external images

Ok, so I want:

  • Take an external image
  • Import it into the canvas object
  • Compression
  • Save

I have everything that works with local images, however trying to import external images into the canvas creates a security error.

Using PHP, I can create a copy of the external file locally:

file_put_contents("copy.jpg", file_get_contents(""));


The problem is that external images can be quite large - up to 3MB and the canvas will be imported before the image is loaded.

Is there any PHP or Javascript code that waits until the file is fully loaded?

Or is there a better way to do this?


source to share

3 answers

You can use jQuery.ajax () and on the sucess callback you control the canvas



If you want to wait for the entire file to load:

document.onload = function(){ //load image };

If you want to wait for your canvas to load:

canvas.onload = function(){ //load image };

This is the easiest way. However, if you want more efficient results, I recommend using jQuery.



Take external image using ajax. Manipulate the canvas inside the success callback, or use another callback function. Here's a demo code


 success: function(success) {




var process = function(input){

// manipulate the canvas here





All Articles