What is the reason for setting my canvas width to match the window's innerWidth in JavaScript, while also ensuring the canvas width is set to 100

I'm struggling to understand why I need to set both the width and height to 100% in CSS AND also set them to match the inner window width and height for my canvas element to display my drawing properly. If I only set one or the other, it just doesn't work. The same issue applies to the height as well. Here's the code snippet:

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>TESTING CANVAS DRAWING</title>
    <style>
      body {
        margin: 0px;
      }

      canvas {
        border: 2px soild black;
        width: 100%;
        height: 100%;
      }
    </style>
  </head>
  <body>
    <canvas>
      Your browser does not support the HTML5 canvas tag.
    </canvas>
    <script>
      //startup code
      let canvas = document.getElementsByTagName("canvas")[0];
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight

      //drawing

      let context = canvas.getContext("2d");
      context.fillRect(659, 327, 100, 100); // pixel coordinates start from the the top right
    </script>
  </body>
</html>

Answer №1

In this scenario, CSS and JavaScript are addressing two distinct sizes. The Canvas element has its own specific dimensions (usually defaulting to 300x150) along with the HTMLElement dimensions that can be managed using CSS. You can define the dimensions in CSS and utilize relative values, for example:

// Initialization code
let canvas = document.getElementsByTagName("canvas")[0];
// canvas.width = window.innerWidth;
// canvas.height = window.innerHeight

// Drawing
let x = 659 * canvas.width / document.body.offsetWidth;
let width = 100 * canvas.width / document.body.offsetWidth;
let y = 327 * canvas.height / document.body.offsetHeight;
let height = 100 * canvas.height / document.body.offsetHeight;
let context = canvas.getContext("2d");
context.fillRect(x, y, width, height); // Pixel coordinates originate from the top right corner

I'm not specifying the values, but visually it should appear similar albeit slightly less defined. Consider it like a monitor; CSS dictates the physical size of the screen while the JS canvas dimensions represent the resolution.

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

Instead of automatically playing, Youtube videos either remain idle or display suggested videos

I am trying to play a specific moment of an embedded Youtube video using some javascript code. At the specified time, I execute the following code: document.getElementById("video").src= "https://www.youtube.com/embed/...?autoplay=1&start=212"; where ...

AnimationHandler does not animate the Three.js Mesh

I've been struggling to animate the exported mesh from my blender. Even the included buffalo mesh that I see animated in the example is not working for me. I've been attempting to replicate it without success. Here's the code, and I think th ...

Merge a pair of observables to create a single combined output

Hey there, I'm currently diving into the world of RxJS and reactive programming. One challenge I'm facing is merging two observables. The first observable contains an array of objects called DefectImages[], while the second observable holds an ar ...

The exported JSON file from the editor is malfunctioning

After importing the obj file into the editor and exporting the geometry to a js file, I encountered an error in Firefox debug saying "Type Error: t1 is undefined". Interestingly, when I changed the model to the .js file exported by MaxExporter with both "E ...

Angular 2 orderByPipe not displaying any results initially

At first, I thought the reason for not displaying anything initially was due to it not being async and returning an empty array. Everything worked fine without the pipe, but the posts weren't shown on startup. After submitting a post, all the posts ap ...

Spring Security 3 does not support the use of static resources

I am facing difficulty in configuring static resources (such as js, css, images) in spring security 3. Here is my configuration file: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="http://www.springframework.org/schema/s ...

Exploring the forEach() and Apply() functions for processing two-dimensional arrays in JavaScript

I'm facing a challenge with handling an array consisting of arrays, each containing three elements. My goal is to execute the function calcMe(a,b,c){...} for every element in my main array using the forEach() method. However, I find myself stuck and u ...

Tips for concealing a product item when the price is listed as 0

I am facing an issue where some of my products have a price of 0. In order to address this problem, I would like to hide those products from the collection pages. My question is: How can I hide the .productItem or .ItemOrj if the .productPrice span is eq ...

The Transition Division Is Malfunctioning

I've encountered an issue where I am trying to move a div by adjusting its left property, but no transition is taking place. Regardless of the changes I make to my code, the result remains the same. Below is the current state of the code. Can anyone i ...

The PHP query statement is encountering an unspecified parameter

I've been working on code to update a single entry in a SQL database, specifically targeting the invoice ID number ($num). However, I seem to be passing it incorrectly as my console is showing an Undefined value for the idinvoice. Interestingly, now ...

Tips for resolving an ongoing issue of infinite Jquery Polling

I am looking to automatically refresh a page every 3 minutes. The page contains a table where each row represents a post detail. Users are able to reply to the posts, and any new notifications will be displayed as a red bubble with the number of unread me ...

The status in the Network Tab indicates 'Pending' for Axios Request

I encountered some CORS errors when trying to fetch data from an API at https://api.data.io/api/v1 in my React app, so I decided to set up a proxy server. However, after setting up the proxy server, I noticed that no data was being returned when making re ...

How come I am unable to pass JavaScript values to my PHP5 code?

I'm struggling with this code snippet: <?php $html=file_get_contents('testmaker_html.html'); echo $html; ?> <script type="text/javascript"> document.getElementById('save_finaly_TEST').addEventLis ...

"An issue with IE9 causing small dots on rounded corners during rendering

Help Needed: Strange IE9 Rendering Issue I'm experiencing an odd rendering problem in Internet Explorer 9. You see those little white dots on the left? What could be causing them? Any suggestions on how to remove them? Microsoft, why always so myst ...

Enhance the efficiency of AngularJS search filtering

With nearly 2000 rows on this page, I am using AngularJS filter to search for items containing the typed strings. However, I have noticed that the efficiency is poor when typing just one character into the input control. Does anyone have suggestions for im ...

Not all mobile browsers support centering, but regular browsers work flawlessly

For some reason, I am experiencing an issue with centering divs on mobile browsers. It works perfectly fine on normal PC browsers - no issues at all =D. However, the main content on mobile devices remains stuck to the left. I have tried multiple solutions ...

Using the Jquery .on(change) event on a <select> input will only alter the first row

I need help with a table that allows users to add rows. Within the table, there is a select input that triggers an ajax call to update values in another select field. The issue I'm facing is that when a new row is added, the .on(change) event affect ...

Retrieve an image located outside of a container

I have multiple SVGs inside separate div elements. <div id="divA"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <rect x="10" y="10" height="130" width="500" style="fill: #000000"/> ...

What is the best approach to structure a React project in which a component's rendering changes with each instance?

I am facing a challenge with rendering a component that relies on multiple AJAX calls to complete. These AJAX responses return different data each time, and I want to implement a button that will trigger the re-rendering of this random component every time ...

Transmission of state modifications in React

My React project is organized with the following hierarchy: The main A component consists of child components B and C If I trigger a setState function in component B, will components A and C receive notification and potentially re-render during the recon ...