0

I'm drawing an image on my canvas and trying to use getImageData() from canvas to get the image data but I got all 0's in return. From my understanding, the image hasn't finished a load so I get the 0's. From this issue: getImageData always returning 0 seems like I need to wait by using onload. Is there another way to get the data by not use onload function? I want to declare an image tag in my html. Here is my code:

<html>

<head>

</head>

<body>
    <script>
        var bgMap = {
            "bg1": "image1.JPG",
            "bg2": "image2.JPG"
        }
    </script>
    <center>
        <select id="selectBg" onchange="document.getElementById('bgImage').src = bgMap[this.value]">
            <option value="bg1">Bg1</option>
            <option value="bg2">Bg2</option>
        </select>
    </center>
    <img id='bgImage' src='image1.JPG' width=500 height=500 />
    <canvas id='bgCanvas'></canvas>
    <script>
        var canvas = document.getElementById('bgCanvas')
        var bgImage = document.getElementById('bgImage')
        canvas.width = 500
        canvas.height = 500
        var ctx = canvas.getContext("2d")
        ctx.drawImage(bgImage, 0, 0, 500, 500)
        var imageData = ctx.getImageData(0, 0, 500, 500)
        var rgba = imageData.data;
        for (var px = 0, ct = 500 * 500 * 4; px < ct; px += 4) {
            var r = rgba[px];
            var g = rgba[px + 1];
            var b = rgba[px + 2];
            var a = rgba[px + 3];
            console.log(r,g,b,a)
        }
        console.log(rgba)
    </script>

</body>

</html>
LotOfQuestion
  • 65
  • 2
  • 6
  • *"Is there another way to get the data by not use onload function?"* Why would you not want to do it with `onload` (or at least, the `load` event)? That's the right way to do it, you've *found* that that's the right way to do it, so...? – T.J. Crowder Sep 28 '19 at 10:44
  • I'm still new in html and js and I just saw the way to draw an image on canvas from this issue [link]https://stackoverflow.com/questions/1445862/possible-to-use-html-images-like-canvas-with-getimagedata-putimagedata which has `onload` as an option. So is my idea impossible? – LotOfQuestion Sep 28 '19 at 10:52
  • By the way, Is there any way to return the data from `onload` function? – LotOfQuestion Sep 28 '19 at 14:43
  • See [this](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) and [this](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron). – T.J. Crowder Sep 28 '19 at 15:26

0 Answers0