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

血红的双手。 提交于 2019-11-30 15:22:53

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

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>
austinbv

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.

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