javascripthtmlcanvas

JavaScript: getting ImageData without canvas


Is it possible to get an ImageData Object from an image which is not on the canvas but somewhere else in the DOM tree as a normal <img> ?

If yes, how?


Solution

  • You have to create an in memory canvas and then draw on this canvas the image :

    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    var img = document.getElementById('myimg');
    canvas.width = img.width;
    canvas.height = img.height;
    context.drawImage(img, 0, 0 );
    var myData = context.getImageData(0, 0, img.width, img.height);
    

    But this won't work if the image comes from another domain. This is a security restriction you can't get around if you have no control of the server (be careful that if you open your html file with file:// you'll have a lot of additional restrictions, use http://)