简体   繁体   English

如何使用JavaScript检查HTML5 canvas元素是否在给定坐标区域中包含某些内容

[英]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. 我目前正在使用Chart.js在项目中生成条形图。 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. 我已经将其设置为通过ASP.NET网络方法将数据返回到图表,并且已将其设置为使用静态标签。

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. 我通过在onComplete回调之后迭代数据集和数据,然后使用fillText命令写入画布来完成此操作。

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. 我是一位经验丰富的程序员,但对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 当前项目资源:JavaScript,JQuery,Chart.js,引导程序,ASP.NET Web方法

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? 参考1: HTML Canvas中的getPixel?

Reference 2: How to use JavaScript or jQuery to read a pixel of an image when user clicks it? 参考2: 当用户单击图像时,如何使用JavaScript或jQuery读取图像的像素?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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