plotly.js

The open source JavaScript graphing library that powers Plotly

Show Sidebar Hide Sidebar
Plotly.js

WebGL Heatmaps in plotly.js

How to make webGL based heatmaps in Javascript with Plotly.

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();
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.