I have a rectangular shape that has been rotated using the ctx.rotate
method, and there is also an arc on the canvas. My goal is to determine if any part of the rectangle lies within the boundaries of the arc. See the example below:
https://i.sstatic.net/URAbG.png
I attempted to use the isPointInPath
function but encountered an issue where the coordinates being checked were not the actual coordinates of the rotated rectangle (the actual coordinates are green, while isPointInPath
checks against blue):
https://i.sstatic.net/h6c6w.png
Below is the JavaScript code snippet:
var canvas = document.querySelector('#canvas'),
height = canvas.height = canvas.clientHeight,
width = canvas.width = canvas.clientWidth,
ctx = canvas.getContext('2d');
canvas.width = canvas.height = 512;
var shipx = 400,
shipy = 256;
function moveShip() {
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(shipx, shipy);
ctx.rotate(3.66);
ctx.fillStyle = 'green';
ctx.fillRect(0, 0, 80, 20);
ctx.restore();
// This is what isPointInPath is seeing
ctx.fillStyle = 'rgba(0,0,255,0.5)';
ctx.fillRect(shipx, shipy, 80, 20);
ctx.fillStyle = 'rgba(255,0,0,0.5)';
ctx.beginPath();
ctx.moveTo(256, 256);
ctx.arc(256, 256, 100, -20 * Math.PI / 180, 90 * Math.PI / 180);
ctx.lineTo(256, 256);
if (ctx.isPointInPath(shipx, shipy) || ctx.isPointInPath(shipx + 20, shipy + 20)) {
// This *should* trigger
ctx.fillStyle = 'rgba(0,0,255,0.5)';
};
ctx.fill();
}
moveShip();