簡體   English   中英

有沒有辦法檢測一個點在旋轉和平移后是否在 Path2D 對象中?

[英]Is there a way to detect if a point is in a Path2D object after it has been rotated and translated?

我正在嘗試使用 JavaScript 在 HTML5 畫布中的 Path2D 對象中找到一個點。

var path = new Path2D;
path.rect(0,0,100,100);
// declare the path

ctx.beginPath(); 
ctx.save()
ctx.translate(500,500);
ctx.rotate(Math.PI/2);
ctx.fill(path);
ctx.restore()
// draw the path after translation and rotation

ctx.isPointInPath(path,505,500) // return false because path is defined at 0, 0 not 500,500 where path is drawn
// Is there a way know if the points are in the path where it is drawn.
// I do not want to re - define the path, but if there is a way to move it that would work.

請理解此代碼已簡化,並且我使用的路徑不是通用形狀,因此這需要適用於任何給定的 2d 路徑。 這不是關於語法的問題,所以請原諒未定義的變量。

isPointInPath()將其xy坐標視為未轉換,即作為畫布上的絕對坐標,但它確實在給定的path上應用了轉換。

所以你需要用應用的轉換來調用它(即擺脫這個ctx.restore() )。

但是你的數字不加起來:

 const canvas = document.getElementById('canvas') const ctx = canvas.getContext('2d'); const path = new Path2D; path.rect(0,0,100,100); // declare the path ctx.translate(500,500); ctx.rotate(Math.PI / 2) ctx.fillStyle = "green"; ctx.fill(path); // using fixed values const x = 505; const y = 500; console.log(ctx.isPointInPath(path,x,y)); // reset to identity matrix ctx.setTransform(1,0,0,1,0,0); ctx.fillStyle = "red"; ctx.fillRect(x-2,y-2,4,4); document.scrollingElement.scrollBy(600, 650);
 <canvas id="canvas" width="600" height="650"></canvas>

但是如果您使用正確的坐標,它將按預期工作:

 const canvas = document.getElementById('canvas') const ctx = canvas.getContext('2d'); const path = new Path2D; path.rect(0,0,100,100); // declare the path ctx.translate(500,500); ctx.rotate(Math.PI / 2) ctx.fillStyle = "green"; ctx.fill(path); // using fixed values const x = 495; const y = 505; console.log(ctx.isPointInPath(path,x,y)); // reset to identity matrix ctx.setTransform(1,0,0,1,0,0); ctx.fillStyle = "red"; ctx.fillRect(x-2,y-2,4,4); document.scrollingElement.scrollBy(600, 650);
 <canvas id="canvas" width="600" height="650"></canvas>

如果有一天你真的需要轉換一個 Path2D 對象,你可以參考這篇文章,它使用Path2D.add(path, matrix)的第二個參數matrix來返回 Path2D 對象的轉換副本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM