Unable to use window dimensions in Canvas properties

I'm just starting to explore html, css, and js, and I'm currently experimenting with canvas. My goal is to create a canvas that dynamically adjusts its size based on the window dimensions. Additionally, I want to draw a smaller rectangle within the canvas to use as the base for a maze game. So far, I've managed to resize the canvas along with the window, but I had to set the body's overflow:hidden property which seems to have caused some issues. When I attempt to draw the inner rectangle by setting its width to half of the window size, it ends up extending beyond the screen boundaries. What am I missing here? I simply want the inner rectangle to be clearly visible within the main canvas area.

JS:

$(document).ready(function() {

var ctx;
var ww;
var wh;

drawCanvas();

$(window).resize(function() {
ctx.clearRect(0, 0, ww, wh);
drawCanvas();
});

function drawCanvas() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ww = window.innerWidth;
wh = window.innerHeight;

ctx.canvas.width = ww;
ctx.canvas.height = wh;
ctx.fillStyle ="blue";
ctx.fillRect(0, 0, ww, wh);

ctx.strokeStyle = 'orange';
ctx.strokeRect(10, 20, ww/2, wh/2);

}

});

HTML:

<html>
<head>
<link href="maze2.css" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" type="text/css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js" type="text/javascript" ></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" type="text/javascript"></script>


<script src="maze2.js" type="text/javascript"></script>
<title>Maze</title>
</head>




<body>


<canvas id="canvas">Your browser does not support Canvas.</canvas>



</body>
</html>

CSS:

body {
width: 100%;
height: 100%;
margin:0px;
overflow:hidden;
}

#canvas {
width:100%;
height:100%;
margin:0px;
}

Answer №1

For a seamless canvas experience on your screen, ensure that your CSS is configured to cover the entire physical screen (inner screen). Following these steps will make it work like a charm.

Avoid using window width and height; instead, size the canvas appropriately with CSS and utilize the canvas clientWidth and height properties.

$(document).ready(function() {
   var canvas = document.getElementById('canvas');
   var ctx = canvas.getContext('2d');
   var cW;
   var cH;
   size();
   drawCanvas();

   $(window).resize(function() {
       size();
       drawCanvas();
   });

   function size(){
      cW = canvas.clientWidth; // this should work if your CSS is set up correctly
      cH = canvas.clientHeight;
      canvas.width = cW; // the canvas will automatically clear if the size changes
      canvas.height = cH;
   }

   function drawCanvas() {
     ctx.fillStyle ="blue";
     ctx.fillRect(0, 0, cW, cH);

     ctx.strokeStyle = 'orange';
     ctx.strokeRect(10, 20, cW/2, cH/2);

   }
});

Next time, remember to format your code properly for better readability.

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

What techniques can I use to generate code dynamically for transferring an object to a different Node process?

I'm in the process of developing a node server that must execute potentially unsafe code. To ensure security, I am utilizing a Sandbox API that guards against attacks and provides results and outputs from scripts. This API employs a modified global ob ...

Incorporating Ace Editor into a jQuery UI Resizable Element

I am attempting to create a resizable Ace editor by placing it inside a resizable component. Despite my efforts with the jQuery UI Resizable component, I am unable to get the ace editor to display within the resizable component. Code: <!doctype html> ...

Sequence of text array contains a gap

I'm struggling with a simple array text sequence where A, B, and C need to show for 2500ms each before cycling back through. Currently, there is a blank frame displayed for 2500ms that I can't seem to get rid of. Does anyone have a solution to ...

Implementing a switch feature with enable/disable functionality in a material table using table row data

Is there a way to incorporate an additional action in the Material table and have it included in the React material table along with the element? Furthermore, how can I obtain row data on onChange event while currently rendering it in the state? I would a ...

Is there a period, question mark, apostrophe, or space in the input string?

Currently, I am in the process of developing a program that can determine if an input string includes a period, question mark, colon, or space. If these punctuation marks are not present, the program will return "false". However, if any of them are found, ...

Tips for dynamically adding a style property to an element with ng-class in AngularJS

How can I dynamically change the color of a CSS class after using ng-class and add a property to an existing CSS class? <style> customcss:after{ border-top: 7px solid green; } </style> I want to be able to change the color dynamically using ...

Is UseEffect selectively triggering specific components?

I am attempting to ensure that each time my search field changes, the code within useEffect is executed. Strangely, only console.log('hi') seems to be running while the other code is not. I am struggling to understand why useEffect is choosing t ...

What is the best way to incorporate tooltips in SVG?

My teacher wants me to display a tooltip on an SVG circle with links and information when we hover over it. They suggested using jQuery UI, but I've done extensive research and nothing has been able to assist me so far. ...

The necessary parameters are not provided for [Route: sender] with the [URI: {name}/{code}]. The missing parameters are name and code

I have encountered a problem while using AJAX and I am struggling to find a solution. Routes: web.php Route::get('/{name}/{code}', 'TestController@counter'); Route::post('/{name}/{code}', 'TestController@sender')-&g ...

Protect your dynamic box title in shinydashboard from HTML escapement

Is there a way to dynamically update the title of a container within a shinydashboard using the selection made in a selectInput(), even when dealing with unescaped HTML? library(shiny) library(shinydashboard) library(htmltools) ui <- dashboardPage( ...

Issue with React Material UI Menu not closing properly

I am struggling to close this menu once it is opened on the page, despite trying various methods like moving the icon button tags around. const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, menuButton: { marginRight: theme.s ...

What's the optimal method to preserve extensive article content with Firebase and Vue.js?

Utilizing Firebase and Vue for my dynamic website, I aim to include a section with numerous article pages structured as follows: <article> <!-- order of these elements will not change --> <h1>Article title</h1> <div id="date ...

Cannot retrieve top 2 values from an object - Angular 6 bug fixing issue

I've been attempting to identify the top 2 values in an object within an array, but I'm encountering issues. Previously, I successfully achieved this with average values that were not within an array, however, when looping through some results an ...

Customize the background color in VueJS based on user roles

I am currently working on a vuejs project with different user levels. In the "user" level (and public area), there is a background image, while in the "admin" level, a plain white background is displayed. I have read that using style tags in the template ...

What is the best way to extract both the link and text from an <a> tag that contains another element in XPath?

In a similar way to my current data (which cannot be shared due to company policy), the example below is based on information extracted from this response and this response. The aim is to extract both the text of the <a> element and the link itself. ...

What steps can be taken to ensure that events are triggered on the correct DIV element?

I am considering two different HTML structures for my project: <div id="threeJSContainer"> </div> <div id="UIControls"> <div ng-include src="'scripts/angular/UI.html'"></div> </div> When using the first c ...

What is the best way to execute my node script with a shell script file?

Currently, I'm working on a personal website using node to help me organize the ebooks I'm reading. Right now, my process involves moving to the project folder and running node server.js. I had an idea to create a shell script so that all I hav ...

Using Jquery to dynamically change the font color depending on the value retrieved from the SQL query结果

I am trying to dynamically change the font color of a div using jQuery. The content inside the div is generated from an SQL query. Previously, I used the following jQuery code: $(document).ready(function(){ $('#foo').each(function(){ ...

Animate the transition between the icon and extended variant in Material-UI FAB

If you have a Material-UI FAB with the following code: <Fab size="medium" color="primary" aria-label="add"> <AddIcon /> </Fab> And you want to toggle to this other state: <Fab var ...

A comprehensive guide on incorporating Jest for testing localStorage

I have attempted to mock localStorage following the advice from another source, but I am struggling to get the tests to pass despite several attempts. Below is the code for the localStorage mock: class LocalStorageMock { constructor() { this.stor ...