Page 1 of 1

Canvas dimensions according to window size

Posted: 04 Jan 2015, 14:01
by MarPlo
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.

Canvas dimensions according to window size

Posted: 04 Jan 2015, 14:05
by Admin
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>