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.
MarPlo
Posts:186

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.

Admin Posts:805
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">
<head>
<meta charset="utf-8" />
<title>Title</title>
<style>
#canvas {
  position: relative;
  display: block;
  margin: 5px auto;
  border: 1px solid #0001fe;
  background: #fefe01;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="450"></canvas>

<script>
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;
}
setCanvasSize(cav);

// change canvas dimensions when window resize
window.addEventListener('resize', function(){setCanvasSize(cav);});
</script>
</body>
</html>

Similar Topics