Troubleshooting problem with strokeRect on canvas following a CSS transform rotate(90deg)

English is not my strong suit, so please bear with me.

Let me outline the issue I'm currently grappling with.

I'm in the process of developing a function that allows users to draw a rectangle on a canvas using their mouse (specifically, using the strokeRect function).

Everything works smoothly under normal circumstances. However, when the rotation button is clicked, an issue arises wherein the rectangle is not drawn at the mouse coordinates as expected.

To provide context, clicking the rotate button triggers a CSS rotation using transform = 'rotate(90deg)', and retrieves the canvas size within the calcCanvasRect function utilizing the getBoundingClientRect function.

I'm seeking advice on how to tackle this challenge. Help!

Here's the basic structure for reference:

<div class="myContainer">
    <div class="rotation-wrapper">
       <div id="canvasParent">
          <canvas id="view_canvas"></canvas>
       </div>
    </div>
</div>

The complete source code is provided below:

// JavaScript functions and code snippets are available here...

I have experimented with the canvas translate and rotate features but haven't found a satisfactory solution yet. Is there a more efficient approach?

Could there be some aspect or technique that I am overlooking?

Answer №1

To accommodate different co-ordinates for strokeRect on a rotated canvas, you must update the canvasMousemove function.

if (mode === '90') {
    wwViewCanvas.context.strokeRect(mousedown.x, mousedown.y, zoombox.width, zoombox.height);
}
else{
    let rect = wwViewCanvas.canvas.getBoundingClientRect();        
    wwViewCanvas.context.strokeRect(mousedown.y, rect.width-mousedown.x, zoombox.height, -1*zoombox.width);
}

Here is a complete code snippet that functions correctly even on a rotated canvas:

/* JavaScript code goes here */
.myContainer{
    background-color: yellowgreen;
}
canvas {
    border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="myContainer" style="width:620px; height:374px">
    <div class="rotation-wrapper">
        <div id="canvasParent" style="width:600px; height:338px;"></div>            
    </div>
</div>
<div class="text-center">   
    <button type="button" id="rotation_btn" style="width:64px">
        rotation button
    </button>
</div>

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

Using JQuery's appendTo method with a lengthy string of elements that includes a mix of single and double quotes: a step-by-step guide

My content script is fetching data from the server in the form of an array of objects. The structure looks something like this: [ { "lang": "English", "videos": [ { "embed": "<iframe width='100%' height='421px&apo ...

Issue with Jquery functionality when Vue component is duplicated in multiple instances

When developing a custom datetime picker component on Vuejs, I encountered an issue where jQuery was only correctly affecting the first instance of the component on a page. The datetime picker component code in VueJs includes: <div class="date-sec ...

position the cursor at the end of the text within the text box

I am looking to move the cursor to the end of the text inside a text box that already contains text. Is there a way to achieve this using Java Script, CSS, or JQuery? <span> <input id="listInput" class="autocomplete-input singleselect-autocom ...

Contrasting CSS Attribute Selectors and Pseudo-Elements in Input Tags

<input type="text" placeholder="nothing" title="google" required> **CSS Content:** input[type="text"]{ border: 2px solid red; } input::placeholder{ color:green; } input[title="google"]{ background ...

Stacking a Bootstrap column above another column

Is there a way to stack a bootstrap column on top of another column while maintaining its size and responsiveness? Consider this scenario with 4 columns arranged in a row: https://i.sstatic.net/qug0g.png Upon clicking the Overlay btn, the E column shoul ...

Circular picture contained within a Bootstrap column on an irregularly-shaped image file

I am looking to create a circular effect for an image that is originally rectangular, resembling a typical profile picture. I have come across several sources on how to do this. The challenge arises in trying to achieve this effect within a bootstrap colu ...

Having trouble with Google font displaying on React site but not on mobile devices?

After importing a Google font that appears perfectly on desktop and cross-browser, an issue arises on mobile where default fonts are shown instead. Below is a snippet from my App.css file: @import url("https://fonts.googleapis.com/css2?family=Turret+Ro ...

Ways to include a fresh value using an existing key in a document

Is there a way to keep track of multiple categories and their corresponding costs in a category object? For example, if I add the products: $50 category to the user in my code, it displays 'categories': { products: '50$' } in the consol ...

Using Jquery, the index number is returned for each item in an array, and then that index is set as a "rel

I am working on modifying the Jquery Infinite Carousel to resize the image container dynamically based on the currently displayed image. My dilemma lies in obtaining the index of the Li element that contains the current image. The issue is that Infinite Ca ...

Error message in Next.js: Wavesurfer.js encountering an issue - unable to access properties of null (specifically, 'isPaused')

I've encountered an intermittent error while working with controls on my audio player using wavesurfer.js. Below is the error I'm facing: https://i.sstatic.net/u4w8t.png It seems like the error might be related to how I imported wavesurfer in ...

What is the best way to incorporate data types into a React useReducer reducer function?

I originally had a useReducer function in pure react without TypeScript, but now I want to add types to it. Here is the useReducer reducer function in pure react without types: export const cartReducer = (state, action) => { switch (action.type) { ...

Properly managing the Ajax.BeginForm OnSuccess event

I am facing an issue with my code that calls the 'SaveNewSoftware' method. This method will return true if there is no existing software found, and false if software with the same name already exists. My problem is that even when the server call ...

What is the significance of utilizing response.json() for accessing JSON objects on both the server and client sides?

Just starting out with the MEAN stack, I've included my API code below where I'm using res.json(random) to send a random password. module.exports.changePass = function (req, res) { console.log(req.body.email) db.user.find({ where: { name: ...

Learn how to include the srcObject attribute of a video tag and then dynamically inject it into an HTML page using JavaScript or jQuery

media stream object inside console and this is what I am seeing after setting the source attribute The following function is part of my client-side script. I am working on a project that involves WebRTC and this function is called whenever I need to add a ...

The absence of PHP GET variable being set

I am encountering an issue with my registration php class. It is designed to display a form and upon clicking the registration button, it triggers a function in a login javascript file. This JavaScript file utilizes ajax to send data to an index.php file. ...

Search for Azure Time Series Insights (TSI) data insights

Is there a way to access real-time data from Azure TSI using the TSI query API? I am currently utilizing the TSI JavaScript Client library, which provides two wrappers for the Query API. However, these wrappers only allow me to retrieve aggregate data li ...

Methods for displaying a placeholder in a semantic-ui-vue dropdown without using the multiple attribute

When utilizing the dropdown feature in semantic-ui-vue, I have encountered an issue where the placeholder option does not function unless the multiple attribute is included. You can view my sandbox demonstration at this link. I have set up 2 dropdowns: ...

Learn the steps for generating an array of objects in AngularJS or JavaScript

I have an array named $scope.data2 and I am looking to create another array of arrays based on the data provided below: $scope.data2 = [ {"dt":"07 Jul 2015","avgdelay":"10","code_sent_time":"07 Jul 2015 12:30 PM" ...

tips for choosing tags that are nested within specific parent tags

I'm looking to locate and count all the <"a"> tags within every <"code"> tag on a given webpage using JavaScript. How can I accomplish this? I attempted methods like document.getElementsByTagName("code").getElementsByTagName("a"); and doc ...

Exploring geometric materials within the THREE.js framework

I'm currently working on creating a geometry in THREE.js: var dotGeometry = new THREE.Geometry(); dotGeometry.dynamic = true; var createDot = function (group, x, y, z){ group.vertices.push(new THREE.Vector3( x, y, z)); } var width = 300; var he ...