CanvasRenderingContext2D.isPointInStroke() - Web APIs 编辑

The CanvasRenderingContext2D.isPointInStroke() method of the Canvas 2D API reports whether or not the specified point is inside the area contained by the stroking of a path.

Syntax

ctx.isPointInStroke(x, y);
ctx.isPointInStroke(path, x, y);

Parameters

x
The x-axis coordinate of the point to check.
y
The y-axis coordinate of the point to check.
path
A Path2D path to check against. If unspecified, the current path is used.

Return value

Boolean
A Boolean, which is true if the point is inside the area contained by the stroking of a path, otherwise false.

Examples

Checking a point in the current path

This example uses the isPointInStroke() method to check if a point is within the area of the current path's stroke.

HTML

<canvas id="canvas"></canvas>
<p>In stroke: <code id="result">false</code></p>

JavaScript

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const result = document.getElementById('result');

ctx.rect(10, 10, 100, 100);
ctx.stroke();
result.innerText = ctx.isPointInStroke(50, 10);

Result

Checking a point in the specified path

Whenever you move the mouse, this example checks whether the cursor is in the stroke of an elliptical Path2D path. If yes, the ellipse's stroke becomes green, otherwise it is red.

HTML

<canvas id="canvas"></canvas>

JavaScript

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// Create ellipse
const ellipse = new Path2D();
ellipse.ellipse(150, 75, 40, 60, Math.PI * .25, 0, 2 * Math.PI);
ctx.lineWidth = 25;
ctx.strokeStyle = 'red';
ctx.fill(ellipse);
ctx.stroke(ellipse);

// Listen for mouse moves
canvas.addEventListener('mousemove', function(event) {
  // Check whether point is inside ellipse's stroke
  if (ctx.isPointInStroke(ellipse, event.offsetX, event.offsetY)) {
    ctx.strokeStyle = 'green';
  }
  else {
    ctx.strokeStyle = 'red';
  }

  // Draw ellipse
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fill(ellipse);
  ctx.stroke(ellipse);
});

Result

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'CanvasRenderingContext2D.isPointInStroke' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:32 次

字数:5435

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文