0

I want to get the pixel data from an image. When I run my code as is, with a rectangle drawn on the canvas, it alerts me with the color information for the top left most pixel. When I try the same thing while drawing only the image on the canvas I get nothing. I have been searching for possible reasons. I thought possibly the image isn't finished loading yet when it tries to create the image data so I added the on load function to make sure. I saw a very similar post which made me think it was a security issue but I tried changing the image cross origin to anonymous which didn't change anything. I'm just not sure where else to look thank you for any help.

<html>
<head>
</head>
<body style="margin:0px">
<canvas id="canvas1" width="400" height="300" style="border:1px solid #000000;"></canvas>   
<script>

    var loaded = false;
    var ctx = document.getElementById("canvas1").getContext("2d");
    var img = new Image();
    img.src = "img/dirt.png";
        
    img.onload = function(){
        loaded = true;
        update();
    }
            
    function update() {
        ctx.fillStyle = "red";
        ctx.fillRect(0,0,50,50);
        //ctx.drawImage(img,0,0);
        var imgData = ctx.getImageData(0, 0, 1, 1);
        ctx.putImageData(imgData, 100, 0);
        alert(imgData.data[0] + " " + imgData.data[1] + " " + imgData.data[2]);
        
    }
    
</script>
    
</body>
</html>
Kaiido
  • 123,334
  • 13
  • 219
  • 285
code_pizza
  • 11
  • 2
  • "I get nothing". Can you check your [dev-tools console](https://developer.mozilla.org/en-US/docs/Tools/Web_Console) please. There might be something there. Are you somehow running this web-page from a `file://` protocol (in the address bar) or from a real server? – Kaiido Jan 04 '21 at 03:26
  • thanks for the quick reply looks like it is a Cross-Origin Request Blocked. I am not running from a real server at the moment. Is it possible to get the request to be accepted for testing – code_pizza Jan 04 '21 at 03:37
  • The best is to run a local server. Depending on your system it may be as simple as a single-line in the terminal to set up one. – Kaiido Jan 04 '21 at 03:39
  • fantastic thank you – code_pizza Jan 04 '21 at 03:51

0 Answers0