![](/img/trans.png)
[英]how Calculate the rubberband coordinates of a rotated shape in canvas - javascript
[英]Javascript: How to find a specific shape on a canvas based on click coordinates
我有一個正方形網格,在 canvas 中,我能夠完美地獲得 canvas 內的點擊坐標。 我想知道如何在這些坐標處找到形狀。 這是代碼:
ngOnInit(): void {
const canvas = document.getElementById('myCanvas');
const ctxGrid = canvas.getContext('2d');
ctxGrid.lineWidth = 0.1;
canvas.addEventListener('mousedown', onDown, false);
//grid with rectangles
for (let i = 0; i < 50; i++) {
for (let j = 0; j < 25; j++) {
//variables
let x = i * 20;
let y = j * 20;
let l = 20, w = 20;
//push the square info
this.shapes.push({ x, y, l, w }) //array of objects storing the information of the rectangle
//draw it
ctxGrid.strokeRect(x, y, l, w);
}
}
function onDown(event) {
const rect = canvas.getBoundingClientRect()
let cx = event.clientX - rect.left;
let cy = event.clientY - rect.top;
console.log(cx + ", " + cy);
}
}
這是 HTML:
<canvas id="myCanvas" width="1000" height="500">
</canvas>
我想到了。 由於我創建了一個包含每個矩形信息的對象數組,因此我只使用坐標並使用循環比較所有正方形信息對象的坐標,並使用正確正方形的索引!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.