Canvas dimensions according to window size

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Posts: 142

Canvas dimensions according to window size

Hi all,
How can I set the canvas dimensions (width and height) according to window's size, using JavaScript?
And, if it's possible, to change canvas dimensions when window resize.
For example, the canvas width and height to be set and remain 90% of window size.

With self.innerWidth and self.innerHeight you can get the window's width and height. Then, with "resize" event you can detect when the window is resized.
See this code:

Code: Select all

<!doctype html>
<html lang="en">
<meta charset="utf-8" />
#canvas {
  position: relative;
  display: block;
  margin: 5px auto;
  border: 1px solid #0001fe;
  background: #fefe01;
<canvas id="canvas" width="600" height="450"></canvas>

var cav = document.getElementById('canvas');  // get canvas element

// sets canvas (c) dimensions 90% of window's size
function setCanvasSize(c) {
  c.width = self.innerWidth * 0.9;
  c.height = self.innerHeight * 0.9;

// change canvas dimensions when window resize
window.addEventListener('resize', function(){setCanvasSize(cav);});

Similar Topics