Check if a rotated rectangle lies within the circular boundary of the canvas

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();

Feel free to play with the live code in JSBin

Answer №1

To align the rectangle with the system, a simple coordinate rotation can be used followed by applying one of the various axis-aligned algorithms that suit your specific scenario:

let deltaX = target.x - object.x,
    deltaY = target.y - object.y;

context.rotate( -object.rotation );

context.beginPath();
context.moveTo(0, 0);
context.arc(0, 0, target.radius, target.startRotation, target.endRotation);

if (context.isPointInPath(deltaX, deltaY) ||
    context.isPointInPath(deltaX + rect.width, deltaY) ||
    context.isPointInPath(deltaX, deltaY + rect.height) ||
    context.isPointInPath(deltaX + rect.width, deltaY + rect.height)) {

    checkCollision();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing HTML's multiple input type color feature to save selected colors directly to the database

I am currently using the input type color to select colors for customizing my site. I save the selected color to a database and then retrieve it to apply it to different areas of the site. This works well for a single input type color, but now I have mul ...

What could be causing ng-repeat to malfunction?

My ng-repeat is not working with the table - only the header part is being displayed in the output. I have checked my binding and it seems to be correct, but I know I am missing something. Can someone please help me figure out what I am doing wrong? JAVA ...

Acquire the content of an interactive website with Python without using the onclick event

I am looking to extract the content of a dynamically generated website after clicking on a specific link. The link is structured as follows: <a onclick="function(); return false" href="#">Link</a> This setup prevents me from directly accessin ...

Is there a way to implement jQuery.closest() using DOM manipulation or pure JavaScript?

Here is the HTML I am attempting to target. Given this HTML structure: <table class="non-unique-identifier table"> <tr><td><div id="unique-identifier"></div></td></tr> </table> I am trying to select #unique ...

javascript - substitute the dash (hyphen) with a blank space

For quite some time now, I've been on the lookout for a solution that can transform a dash (hyphen) into a space. Surprisingly, despite finding numerous responses for changing a space into a dash, there seems to be a scarcity of information going in t ...

Difficulties encountered when attempting to populate a select dropdown with data fetched through an AJAX request

Currently, I am working on a small project that involves managing libraries. One of the tasks at hand is populating a select tag with all the libraries stored in my database. To accomplish this, I have developed a WebService which features a web method cal ...

Ways to alter the div post user authentication

I'm in the process of developing a website with a single-page application setup. I'm utilizing Node.js for the backend and Angular for the frontend. The challenge I'm facing is displaying a specific div when a user is not logged in, and swit ...

Ensure that only one button from the collection is activated

One of the features on my website includes 3 blocks with buttons. These buttons trigger a change in the displayed picture when clicked. However, it is crucial to ensure that when a new track is activated, the previous button returns to its original state. ...

Error encountered in NEXT JS: Unable to parse URL from /api/projects or Error message: Failed to connect to 127.0.0.1:3000

Currently utilizing: export const getStaticProps = async () => { export const getStaticPaths = async () => { and accessing my API (pages/api/projects/) created with Next.js on my local host const res = await fetch("http://localhost:3000/api/ ...

Rendering a ImageBitMap/Image on an OffScreenCanvas using a web-worker

In my vue.js application, I have implemented vue-workers/web-workers to handle image processing tasks such as scaling and cropping in the background after a user uploads images. Due to the lack of support for Canvas and Image Object in web workers, I opte ...

Automatically execute a function when the number input changes, but only if no further changes are detected after a certain period of time

I am implementing angularjs with an input field for numbers. I want to trigger an action automatically after a certain amount of time, but only if no further changes have been made to the number within that time frame (let's say 2 seconds). In my exa ...

Ways to stop values from being turned into strings in javascript?

let str; let displayedNum; for (let i in imgURLArray){ str = "<li photonum="+i+">" + "<a>"+ (1+i) + "</a>" + "</li>"; $("ul.selection-list").append(str); } While looping through, I encountered an issue wher ...

What is preventing me from modifying the data in a JSON object?

My task is to update the value "customer.signature", but I am facing an issue with my code. The JSON and HTML seem to be error-free, so the problem lies within my JS code. While "data.signature" updates correctly, "data.customer.signature" does not. The J ...

Transmit a pair of data values to the ajax request

How can I send two parameters to my JavaScript and retrieve them in a PHP file? Here is my HTML: <form method="post" action="testButtonSup.php"> <p> Please choose the service:<br /> <input type="radio" n ...

Replace the value of a variable when another variable becomes false in Angular.js

Currently, I am working on a project using Angular and have run into an issue that I need help with: In my project, I have two variables - signed which is a boolean bound to a checkbox, and grade which is an integer bound to a number input field. I am lo ...

Please consider opening in a new tab rather than a new window

<a href='#' onclick="loadpage();">[RANDOM PAGE]</a> Whenever this code is clicked, the following function gets executed. function loadpage(){ $.ajax ({ type: "POST", url: "fetchpage.php", data: "showpage=1", success: function(msg) { ...

My VW controller is receiving null from AJAX

Hey there, I've been dealing with this issue for a few hours now and still haven't found a solution. All my request data looks good except for subscriptionTag, as it always comes back as null when the request is sent to the server. I even tried ...

Animation issue in Material UI autocomplete label feature

Hello, I am currently delving into the world of React and Material UI. I have been working on implementing the Material UI auto complete feature with chip functionality. You can see my progress here: https://codesandbox.io/s/runh6. Everything seems to be w ...

Errors occur when attempting to install plugins from npm

I am currently coding in Visual Studio 2017 using Ionic v2 to develop an app for beacon scanning. However, every time I try to install a plugin, I encounter errors from npm about the versions of node and npm being incompatible. Here are my current versions ...

Vue's bidirectional data binding presents a challenge when attempting to update the parent component from a child component

I have the following components: Parent Component: <template> <v-container> <v-row class="text-center"> <v-col cols="12" class="parent"> <p>I am the Parent component</p> ...