Black Lives Matter. Please consider donating to Black Girls Code today.

New User: HeatMap example error

Hi, I’m a new user os Plotly.js and I copy and paste the WebGL Heatmap example to see how it works.
Link here: https://plot.ly/javascript/heatmap-webgl/

But I got this console error:

VM3597:1 Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The source width is 0.
    at eval (eval at processdata (file:///C:/Users/lamar/Desktop/heat_map_js/index.html:19:23), <anonymous>:1:9)
    at processdata (file:///C:/Users/lamar/Desktop/heat_map_js/index.html:28:23)
    at HeatmapGLfromImage (file:///C:/Users/lamar/Desktop/heat_map_js/index.html:15:9)
    at file:///C:/Users/lamar/Desktop/heat_map_js/index.html:61:1

Here is my full source-code:

<html>
    <head>
        <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    </head>
    <body>
        <canvas height="500" id="canvas" style="display: none" width="500"></canvas>
        <!-- Plotly chart will be drawn inside this DIV -->
        <div id="myDiv" style="width: 600px; height: 600px;"></div>
    </body>
    <script>

        function HeatmapGLfromImage() {
            var img = new Image();
            img.setAttribute("src", processdata("https://images.plot.ly/plotly-documentation/images/heatmap-galaxy.jpg"));
        }
        function processdata(url) {
            var canvas = document.getElementById("canvas");
            var img = new Image();
            img.crossOrigin = "anonymous";
            img.src = url;
            var context = canvas.getContext("2d");
            context.drawImage(img, 0, 0);
            var w = img.width;
            var h = img.height;
            var l = w * h;
            var arr = context.getImageData(0, 0, w, h).data;

            var zdata = [];
            for (var i = 0; i < l; i++) { // get color of pixel
                var r = arr[i * 4]; // Red
                var g = arr[i * 4 + 1]; // Green
                var b = arr[i * 4 + 2]; // Blue
                var a = arr[i * 4 + 3]; // Alpha
                zdata.push(r + g + b + a);
            }
            var createGroupedArray = function (arr, chunkSize) {
                var groups = [],
                    i;
                for (i = 0; i < arr.length; i += chunkSize) {
                    groups.push(arr.slice(i, i + chunkSize));
                }
                return groups;
            };
            // Grouping zdata into 500x500
            var zdata = createGroupedArray(zdata, 500);

            var data = [{
                    z: zdata,
                    type: "heatmapgl",
                    colorscale: "Picnic"
                }];

            Plotly.plot("myDiv", data);
        }

        HeatmapGLfromImage();
    </script>
    
</html>

Could you help me?

Here is a working example: https://codepen.io/plotly/pen/rrvdXv

1 Like