How to select lines that are drawn on a HTML5 Canvas?

試著忘記壹切 提交于 2019-11-30 15:48:58

问题


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.


回答1:


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;
});



回答2:


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>



回答3:


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.



来源:https://stackoverflow.com/questions/8184452/how-to-select-lines-that-are-drawn-on-a-html5-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!