简体   繁体   中英

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

I am currently working with Chart.js to generate bar graphs in a project. I've set it up to return data to the chart through an ASP.NET webmethod, and I've set it up to use static labels.

I've done this by iterating through the datasets and data after the onComplete callback, then using the fillText command to write onto the canvas.

Now, I'm having the issue where labels sometimes overlap or overlap with the contents of the chart.

What I want to do is check if the canvas already has something on it at a given point / region. Is this possible? If so, how can it be done?

I'm an experienced programmer but am very new to JavaScript. I searched for a few hours trying to find a suitable solution but could not find anything that worked correctly.

I can provide sample code and images if needed, but I do not think it is required given the scope of the question.

Current project resources: JavaScript, JQuery, Chart.js, bootstrap, ASP.NET webmethods

Thank you

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM