Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

javascript - Is there a native way to address a non-rectangle object on canvas in js?

I've created a grid of several distorted rectangles made with Bezier curves. Each rectangle has its own color on the picture.

Let's say, I want to add hover effect for each of these rectangles, therefore I need to know its dimensions. Since I can fill or stroke the figure I assume that there is some way to get them, but I'm not sure.

Here is the example of the rectangles:

enter image description here

So the question is, is there some method in the canvas API with which I can achieve the desired effect?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes you can use isPointInPath(Path2D, x, y) method.

Note that if you don't use the Path2D object, you can also call it just with isPointInPath(x, y), but then it will check on the currently being drawn path (declared with beginPath()).

var ctx = canvas.getContext('2d');
var myPath = new Path2D();
myPath.bezierCurveTo(50, 100, 180, 10, 20, 10);
myPath.lineTo(50, 100);

function draw(hover) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = hover ? 'red' : 'green';
  ctx.fill(myPath);
}

canvas.onmousemove = function(e) {
  var x = e.clientX - canvas.offsetLeft,
    y = e.clientY - canvas.offsetTop;
  var hover = ctx.isPointInPath(myPath, x, y)
  draw(hover)
};
draw();
<canvas id="canvas"></canvas>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...