Question

<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');
  var img = new Image();
  img.onload = function(){
    canvas.width=img.width;
    canvas.height=img.height;
    context.drawImage(img,0,0);
  }
  img.src="2.jpg";
  function compress(){
    var dataURL = canvas.toDataURL("image/jpg",0.5);
    document.getElementById("img").src=dataURL;
  }          
  setTimeout(compress,1000);
</script>

I've tried to use as example fillRect() instead of drawImage(). So it works normally... I'm sure that reason is drawImage()

Was it helpful?

Solution

If your image URL (the original URL, not the data URL) is from a different domain than that of the page where the code runs, then the canvas will be tainted when you draw the image to it, and you wont be able to get the pixels back out. That's a security measure. Thus if you're testing on jsfiddle and you're using http://placekitten.com/100/100 urls to test, it won't work.

Note that most modern browsers do not consider two file:// URLs to share a domain, so if you're running the test from local files, it won't work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top