1

So I'm trying to write an image filter using the HTML5 canvas, but before I can do that, I need to be able to draw images onto the canvas. I tried a few things and ended up finding many sources saying that the image.crossOrigin property had to be set to "anonymous" before setting the source of the image. I tried this and copied some code that apparently worked for some others but still wasn't able to get it to work.

This code is at the bottom of the body tag, with draw being called from body's onclick property.

Code:

<script>
function draw() {
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    var img = new Image();
    img.onload = function(){
        context.drawImage(img, 40, 40);
    }
    img.crossOrigin = "Anonymous";
    img.src = "field.jpg";
}
</script>

The image's link is local, but I also tried with a dropbox link for the same image and neither worked.

Error with local file:

Image from origin 'file://' has been blocked from loading by Cross-Origin Resource Sharing policy: Invalid response. Origin 'null' is therefore not allowed access.

Error with dropbox:

Image from origin 'https://www.dropbox.com' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Can anyone see what I'm doing wrong?

Edit: I'm on chrome for those who wanted to know

gerbot150
  • 11
  • 3
  • Possible duplicate of [CanvasContext2D drawImage() issue](http://stackoverflow.com/questions/32880641/canvascontext2d-drawimage-issue) – Kaiido Oct 28 '15 at 03:18
  • 1
    Yes, you're trying to load images from sources that dont allow you to do so. You need to either install some local server to serve your files, use a file input to gain access to local files or set your browser to allow access to file urls. – LJᛃ Oct 28 '15 at 03:19
  • 2
    @guest271314 if OP realy set the crossOrigin property to `'Anonymous'`, any browser should throw this error since "If the server does not give credentials to the origin site (by not setting the Access-Control-Allow-Origin: HTTP header), the image will be tainted and its usage restricted." [mdn](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-crossorigin) – Kaiido Oct 28 '15 at 03:42

0 Answers0