Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 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 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...