What is the best way to rotate rectangles without moving them on an HTML canvas?

I am encountering difficulties when attempting to rotate rectangles on an HTML canvas in place. In the provided JS Fiddle, you can see the original image displayed here: https://jsfiddle.net/vyx2hbky/. What I aim to achieve is to rotate the lines slightly, perhaps by 45 degrees, while keeping them in their original positions.

Upon uncommenting the commented code in the JS Fiddle, which reads as follows,

ctx.translate(coords[0], coords[1]);
ctx.rotate(Math.PI / 4);

the initial rectangles start behaving erratically and appear messy. They do not rotate in place, causing confusion with how to rectify this issue.

I have reviewed various Stack Overflow inquiries about rotating rectangles around their center point, yet I struggle to identify said center point for each rectangle initially and replicate this process across all rectangles within the canvas.

Experimenting with

ctx.translate(coords[0] + c.width / 2, coords[1] + c.height / 2)
, per suggestions from previous Stack Overflow responses, has proven ineffective. Any advice on how to proceed would be greatly valued!

Answer №1

Here's a neat trick to try out right after the line that says "var coords = dotPositions[i];":

    ctx.save();
    ctx.translate(coords[0]+5, coords[1]);
    ctx.rotate(Math.PI / 4);
    ctx.rect(-5, 0, 10, 0);
    ctx.fill();
    ctx.stroke();
    ctx.restore();

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

Locate a user within an array in Angular 5 by inputting a specific character into a textarea before initiating the search

I'm currently facing a situation with my textarea component... <textarea [(ngModel)]="message" id="commentBox" placeholder="Add your comment here..."></textarea> Additionally, I have a user list that retrieves data from an external API l ...

JavaScript - identifying specified tags within a given string

I have created an array containing some tags: var myArray = [ "mouse", "common", "malcom", "mountain", "melon", "table" ]; Now, I need to extract these defined tags from a given string. For instance, from the string: the mouse is ...

None of the available paths matched with api/v1/users at this moment

I encountered an issue while following a tutorial and I am unable to pinpoint the mistake in my "SignUpView.vue" file. I attempted switching to re_path but it did not resolve the problem. Not Found: /api/v1/users [15/Oct/2023 22:30:42] "POST /api/v1/user ...

Changing a numeric string into a number within an Angular 2 application

Looking for advice on comparing Angular 2 expressions. I have an array of data stored as numeric strings in my database and I need to convert them to numbers before applying a condition with ngClass for styling purposes. Any suggestions on how to perform ...

Position Bootstrap post pagination links at the end of the row in WordPress

My Wordpress custom post type has numeric pagination links within a Bootstrap row instead of appearing below the post thumbnails. How can I move them to a new row below the thumbnails without creating a row within a row? Bootstrap version: 3.3.7 https:// ...

React with Typescript prop is functioning well, despite displaying an error

After creating a component and passing props to styled components, everything seems to be working fine. However, I keep encountering this error on the first prop. Component type WelcomeProps = { image: String, color: String } const StyledWelcom ...

Jpicker is renowned for its transparency feature

I am currently using the Jpicker jpicker-1.1.6.js script which can be found at Below is a snippet of my code: <script type="text/javascript"> $(function() { $.fn.jPicker.defaults.images.clientPath='/img'; var ...

Assistance needed with troubleshooting an HTML and CSS table error

When checking the error console in Opera, I noticed an error related to this line of code: filter:alpha(opacity=99); opacity=0.99; MozOpacity=0.99; I am currently using it in this manner. Any idea what might be causing the issue? ...

Other browsers, such as Chrome and Firefox, are visible, except for Safari

https://testing007.s3-api.us-geo.objectstorage.softlayer.net/1A23CDC6F75811E6BFD706E21CB7534C---prof__6.jpg This link displays correctly on browsers like Chrome and Firefox, but does not show up on Safari. ...

Overriding model methods in SailsJS

As I integrate caching (redis) into my project, my preference is to incorporate it into the model logic rather than the controller. This would involve overwriting the model method and including the caching logic within that. I am aware that certain method ...

Python Selenium- Extract and print text from a dynamic list within a scrolling dropdown element

I am currently working on a project using Selenium and Python to extract a list of company names from a dropdown menu on a javascript-driven webpage. I have successfully managed to reveal the list of company names by clicking the navigation button, and eve ...

Images in Next.js work properly in a local environment, but encounter issues in the production environment

My Next.js images are working fine on local, but when I try to push it to production, it crashes. Here is my code View my image component here This is where I map the images Here is the part of my .json file where I fetch data It works properly in loca ...

Extracting Data from a Highly Nested Document in Mongoose

I am facing a challenge in deleting a deeply nested location object from the locations array. Even after carefully following mongoose documentation, my attempts have not yielded successful results: lists = [{ "listName": "Test", "_id": "8d55f0afe5 ...

How to align a button vertically centered next to a matInput using Angular Material

Is there a way to vertically center a button next to matInput in Angular material? The submit button appears too low compared to the "First Name" input field, as shown in the images below: https://i.sstatic.net/PZGAg.png https://i.sstatic.net/ZuxHc.png ht ...

Retrieve the ngModel's current value

One of the challenges I encountered is with a textarea and checkbox interaction. Specifically, once the checkbox is checked, I aim to have the value appear in the textarea. <div class="message-container"> <textarea *ngIf="mode === 1" ...

Limit the number of elements in an Angular object by using the filter function

I've implemented an angularjs filter method on a repeated array of items in an attempt to filter numbers using a limitTo filter. However, the result is not reflecting in the DOM. Below is the html code snippet: <div ng-controller="demo as d"> ...

Clicking on text will open a popup div using HTML and CSS

I am looking to create a popup div instead of a popup window for my 'About' picture/page with the current button. Here is an example: ...

Struggling to Adjust Image to Fit Within Parent Element

I recently started using bootstrap 4 to create a responsive website for practice. However, I encountered an issue with my image not resizing properly to fit the screen. <html lang="en"> <head> <!-- Required Meta Data --> ...

Utilizing XPath to retrieve text from a hyperlink

I'm currently using Python with Xpath to scrape Reddit, specifically working on extracting links and displaying their titles on the front page. To do this, I'm utilizing the Scrapy framework and conducting tests in the Scrapy shell. I'm stru ...

I am having trouble getting Nodemon to load my index.js file

I've been facing some issues with getting my code to run smoothly. Every time I try to use nodemon to launch it, it attempts to connect but I just see a loading icon in the localhost tab. When using live-server, the homepage loads fine on its own but ...