是否有一种本地方式来解决js中画布上的非矩形对象? [英] Is there a native way to address a non-rectangle object on canvas in js?

查看:170
本文介绍了是否有一种本地方式来解决js中画布上的非矩形对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个由Bezier曲线制作的几个扭曲矩形的网格。每个矩形在图片上都有自己的颜色。

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.

以下是矩形的示例:

所以问题是,是否有一些方法在canvas API中,我可以用它来达到预期的效果吗?

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

推荐答案

是的,你可以使用 isPointInPath(Path2D,x,y)方法。

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

请注意,如果您不使用Path2D对象,您也可以使用 isPointInPath(x,y)调用它,但它会检查当前正在绘制的路径(用 beginPath()声明)。

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>

这篇关于是否有一种本地方式来解决js中画布上的非矩形对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆