Chartjs-How to check if HTML5 canvas element contains something in given coordinate region using javascript

1👍

Well, my requirements changed and I no longer need to worry about this, but I will post the code I used anyways:

var imgData = context.getImageData(0,0,canvas.width,canvas.height);

// Function to find the hex color of a specific pixel in the imgData context.
function getPixel(imgData, index) {
    var i = index * 4, d = imgData.data;
    return rgbToHex(d[i], d[i + 1], d[i + 2]) 
    // returns hex string of rgb values.
}

// Function to caluclate offset of imgData context and then return hex color from getPixel function call.
function getPixelFromCoordinate(imgData, x, y) {
    return getPixel(imgData, y * imgData.width + x);
}

// Function to convert a given rgb value to a hex string.

function rgbToHex(r, g, b) {
    // Left shift values to allow for cheap hex construction
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

This code worked fine, so hopefully it will be helpful to others.

Reference 1: getPixel from HTML Canvas?

Reference 2: How to use JavaScript or jQuery to read a pixel of an image when user clicks it?

Leave a comment