Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

context.getImageData() on localhost?

Tags:

html

canvas

I have the following snippet of code and I'm trying to run it from localhost (OSX, running XAMPP):

var canvas = document.getElementById('mycanvas');
    var cx = canvas.getContext('2d');

    var myImg = new Image();
    myImg.src = 'images/lion.jpg';

    $(myImg).load(function() {
        cx.drawImage(myImg, 0, 0);
        var imgData = cx.getImageData(0,0,150,150);
    });

But when I run it I get this error from the console:

Unable to get image data from canvas because the canvas has been tainted by cross-origin data.
site.js:11Uncaught Error: SECURITY_ERR: DOM Exception 18

I found some similar questions here and I know that this has something to do with the fact that I'm working locally and this wouldn't happen if I was trying to access the image from the same domain. I don't know if this makes sense, but it's what I understood.

My question is, how can I make this work in a local dev environment?

like image 738
Nikolay Dyankov Avatar asked Dec 31 '11 14:12

Nikolay Dyankov


2 Answers

Serve your html with an HTTP server, for example, Apache or Nginx.

Mac OSX comes with Python installed, so you can simply start an HTTP server by opening a terminal, then input:

cd /path/to/my/work/
python -m SimpleHTTPServer

Then open http://localhost:8000/ in your browser. This should work.

like image 78
clowwindy Avatar answered Nov 08 '22 14:11

clowwindy


Trying a different browser might help. This happened to me on Chromium and just by switching to Firefox I was able to continue debugging locally.

like image 33
cangrejo Avatar answered Nov 08 '22 15:11

cangrejo