Reputation: 125
I am using using HTML5 Canvas to plot lines. A single line is formed by calling drawLine() on multiple intermediate points. For example:
(0,0) -> (10, 10) -> (10, 5) -> (20, 12)
would show up as one line on the plot.
All the (x,y) co-ordinates of a line are stored in an array.
I want to provide the users with the ability to select a line when they click on it. It becomes difficult to do this in HTML5 Canvas as the line is not represented by an object. The only option that I am left with is to first find that (x,y) coordinate of any line that is closest to the (x,y) of a mousedown event. Once I detect which line the user has selected, then I need to redraw the line with a bold color or put a translucent color around it. But, I am assuming that this would be too time-intensive, as it involves looping over all (x,y) coordinates of all lines.
I am looking for ways that can help me achieve the above in a more time-efficient manner. Should I consider using SVG in HTML5?
Any suggestions would be appreciated.
Upvotes: 10
Views: 10183
Reputation: 9491
The only way to do this on the canvas is to detect pixel color and follow path or save paths as objects and detect a click on that path.
Upvotes: 1
Reputation: 303261
The simplest way to do this in HTML5 canvas is to take a snapshot of the image data for the canvas, and during mousemove look at the alpha color at the pixel under the mouse.
I've put up a working example of this on my site here:
http://phrogz.net/tmp/canvas_detect_mouseover.html
Here's the core code I wrote. Pass it a context and a function, and it will call your function with the RGBA components underneath the pixel.
function pixelOnMouseOver(ctx,callback){
var canvas = ctx.canvas;
var w = canvas.width, h=canvas.height;
var data = ctx.getImageData(0,0,w,h).data;
canvas.addEventListener('mousemove',function(e){
var idx = (e.offsetY*w + e.offsetX)*4;
var parts = Array.prototype.slice.call(data,idx,idx+4);
callback.apply(ctx,parts);
},false);
}
And here's how it's used on that test page:
var wasOver;
pixelOnMouseOver(ctx,function(r,g,b,a){
var isOver = a > 10; // arbitrary threshold
if (isOver != wasOver){
can.style.backgroundColor = isOver ? '#ff6' : '';
wasOver = isOver;
}
out.innerHTML = "r:"+r+", g:"+g+", b:"+b+", a:"+a;
});
Upvotes: 11
Reputation: 124089
I think you'd find this much easier in SVG. There each line would be a <polyline>
and you could add a onclick handler to do what you want. For example...
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<polyline points="20,20 40,25 60,40 80,120 120,140 200,180"
style="fill:none;stroke:black;stroke-width:5"
onclick="this.style.stroke='red'" />
</svg>
Upvotes: 6