Adjusting element sizes in HTML5 Canvas

I am currently facing an issue with my canvas container, which has a width of 100% and a height of 50%. When I draw lines on it using x and y coordinates like this:

context.moveTo(20, 20);
context.lineTo(50, 20);
context.stroke();

The problem arises when I resize the canvas by resizing the browser window. The drawn lines do not adjust to the new canvas size as shown in this image: https://i.sstatic.net/SgdrM.png

This is how I resize the canvas:

var scale = window.devicePixelRatio;

this.canvas.width = Math.floor(parseInt(this.$canvasPage.css('width')) * scale);
this.canvas.height = Math.floor(parseInt(this.$canvasPage.css('height')) * scale);
this.context.scale(scale, scale);

this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.drawContent();

Does anyone have any suggestions on how to fix this issue? I was thinking about calculating x and y positions but I'm unsure of the maximum coordinates. Are there any better solutions for this problem? I also plan to add rectangles, input fields, and more elements later.

Thank you for your assistance!

Answer №1

In order to modify the distance between context.moveTo and context.lineTo, you can adjust the pixel values accordingly. However, an alternative approach is to use a percentage of the canvas's width for a more dynamic effect:

context.moveTo(0.25 * this.canvas.width, 0.15 * this.canvas.height);
context.lineTo(0.6 * this.canvas.width, 0.15 * this.canvas.height);
context.stroke();

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

The font is functioning properly in digital screen formats, however, it is not displaying correctly in

I have encountered an issue where the code below works on screen media but not in print media: <style type="text/css"> @font-face { font-family: dinregular; src: url('/images/templateImages/template9/din-regular-italic.ttf') } < ...

Creating an atom without any boundaries: A step-by-step guide

While browsing the Atom forum, I stumbled upon a post discussing scripts for enhancing the UI of Atom. I'm curious about where to place these scripts. Should they go in the Atom init script? Any guidance would be highly valued. Visit this link for m ...

Angular js is failing to populate dropdown values

I'm encountering an issue with editing a user object. When clicking the edit button, some values in the form are loading correctly, but three values are not populating even though I'm receiving the data from the service. HTML < ...

What are the guidelines for incorporating tag names in CSS selectors?

I created a button that when clicked, displays a table containing actors. I have named them as follows: <button class="actors">Show actors</button> <table class="actors">...</div> Next, I want to style and access them in my CSS (a ...

Is there a way to align both the horizontal and rotated lines to intersect at a common point in HTML and CSS?

As a beginner, I'm looking to create a structure resembling a thigh, leg, and ankle using thick lines. My aim is to rotate them with animation, ensuring that the joints between the lines mimic those of a knee joint and hip joint. Below is the code sn ...

Guide on successfully importing PDF files in NextJS using Webpack's file-loader without encountering a 404 error

I'm working on my nextjs app and I'm trying to implement a button that, when clicked, downloads a PDF file. I've stored the PDF in public/documents/, imported it, and added it to the link href. However, when I click on the button, I'm e ...

Is there a way to retrieve the day of the week based on the date provided by the user

function retrieveWeekday() { var input = document.getElementById("input"); } <form> <input type="date" placeholder="dd:mm:yy" id="input"/> <input type="button" value="get weekday" onclick="retrieveWeekday()"/> ...

Having trouble with the "initSdk" property being undefined in your React Native Appsflyer integration?

I'm currently facing an issue while trying to integrate AppsFlyer into a react native application. The error I am encountering is "Cannot read property 'initSdk' of undefined" Initially, I imported the react-native-appsflyer module as shown ...

Pass data stored in a PHP array from a PHP file to a JavaScript array in a JS file

I am currently working on passing an array ($phpArray) from a PHP file to a function in a JS file (data.js). I'm having trouble figuring out the right approach. Any ideas? dataInput.php (PHP File) <?PHP $phpArray=[[1,2,3,4,5], [2,3,5,6 ...

The function createVNode does not exist in the context of Vue integrated with Laravel

I've been attempting to replicate a component rendering based on an online example. While it works smoothly in a sample project, it crashes when applied to the official codebase. Here is the content of the blade file being rendered: <html lang=&q ...

The datepickers in jQuery are failing to initialize every time the modal is opened

I have encountered an issue with using modals in my web application to receive user input. The problem arises when a user opens multiple modals one after another - the jQuery datepickers fail to initialize properly for the second modal onwards. It seems th ...

Encountering difficulties linking to a stylesheet or a script in an HTML file delivered by Express server

Currently, I'm facing the challenge of breaking down my Express app code into multiple files. Unfortunately, I am unable to utilize <link href> or <script src> for linking stylesheets or scripts. Below is the relevant snippet from my inde ...

What could be causing the console to display undefined?

Can anyone help me with an issue I'm having while making an AJAX call using fetch and promises? I have successfully displayed the temperatures, but for some reason, the location is showing up as undefined. Here is the code snippet: function getWeat ...

What are the signs of a syntax error in a jQuery event like the one shown below?

One of my forms has an ID attribute of id ='login-form' $('#login-form').submit(function(evt) { $('#login-button').addClass('disabled').val('Please wait...'); evt.preventDefault(); var postData = ...

Guide on retrieving the AWS IAM user in string/json format using STS GetCallerIdentity Caller JS/TS

I am attempting to retrieve the AWS IAM Arn user using the STS GetCallerIdentity API provided by Amazon. The following code successfully logs the correct data in the console. Nevertheless, I am encountering difficulty returning the data as a string or JSON ...

Transform the date time into a carbon instance

Using the date time input field with the code <input type="datetime-local"> returns a formatted date time of yyyy-MM-ddThh:mm. The goal is to convert this format to Y-m-d H:i using the php-carbon Package. An attempt was made with the following code ...

Move through different screens using React JS

Can anyone help me with this issue I'm facing in React Js? I am trying to implement a button that changes to another screen when clicked, but I keep getting an error message: TypeError: Cannot read property 'push' of undefined. I have tried ...

Remove any unnecessary white space and new lines from the HTML code

Is there a way to remove double whitespaces and new lines from my HTML output without altering the ones within textarea and pre tags using PHP? ...

Unable to receive a response after attempting to send an email through XMLHttpRequest

I have been struggling to send emails even after editing the template. I am currently working on creating a subscription box and here is the code I have so far: var x= document.getElementById("emailtxt").value; var uploadFormData = new FormData(); upload ...

Tips for retrieving the chosen value from a dropdown list in HTML

I'm having an issue with exporting specific values from multiple HTML tables into an excel file. My goal is to only export the selected values from each table, with each table being on a separate tab in the excel file. Currently, when I export the ta ...