javascript 如何在 html5 画布中制作可点击的点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10665862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make clickable points in html5 canvas?
提问by Googlebot
I am playing with a simple tutorialfor drawing line in HTML5
canvas. Since, it is based on jQuery, it is easy to add lots of effects to the drawing.
我正在玩一个在画布上画线的简单教程HTML5
。因为它是基于 jQuery 的,所以很容易在绘图中添加很多效果。
How can I make the point clickable/hoverable to add jquery effects upon click/hover (mouseenter/mouseleave)? The points are drawn by
如何使点可点击/可悬停以在点击/悬停(鼠标输入/鼠标离开)时添加 jquery 效果?点是由
c.fillStyle = '#333';
for(var i = 0; i < data.values.length; i ++) {
c.beginPath();
c.arc(getXPixel(i), getYPixel(data.values[i].Y), 4, 0, Math.PI * 2, true);
c.fill();
}
How to add jquery selector? Basically, I want to show the point coordinates upon click or hover.
如何添加jquery选择器?基本上,我想在 click 或 hover 时显示点坐标。
回答by Parth Thakkar
The problem is that jQuery works with DOM and not drawings on canvas. What you need to do is to store those points somewhere and on hovering over the canvas element, check if the coordinates of the mouse relative to the canvas ( i.e. if you place the mouse over the top-left corner of the canvas, coords are [0,0] ) are within the area of the point/shape. If so, the point is hovered over by the mouse and you can display the effect.
问题是 jQuery 使用 DOM 而不是画布上的绘图。您需要做的是将这些点存储在某处并在将鼠标悬停在画布元素上时,检查鼠标相对于画布的坐标(即,如果您将鼠标放在画布的左上角,坐标是 [ 0,0] ) 位于点/形状的区域内。如果是,鼠标悬停在该点上,即可显示效果。
Psuedocode to understand better:
更好理解的伪代码:
// adding shapes to the canvas
var shapes = []; // make that rects for simplicity.
For (condition):
shapes.push ( new Rect(x,y,width,height) );
canvas.rect( x, y, width, height );
// testing hover.
$("#canvas").mousemove(function(e) {
var offsetX = e.pageX - $(this).position().left;
var offsetY = e.pageY - $(this).position().top;
Foreach shape in shapes:
if( shape.contains(offsetX, offsetY) ) // a fictious method, implement it yourself...lookup for collision detection; not exactly that but something like that...
Mouse hovers! do something great.
});
Ok, maybe to find out if a point is contained within a rectangle, you can use something like this:
好吧,也许要找出一个点是否包含在一个矩形内,您可以使用这样的方法:
function contains(rect, x, y) {
return (x >= rect.x &&
x <= rect.x + rect.width &&
y >= rect.y &&
y <= rect.y + rect.height )
}