'Set Canvas size using javascript
I have the following code in html:
<canvas id="myCanvas" width =800 height=800>
I want, instead of specifying the width as 800, to call the JavaScript function getWidth() to get the width e.g.
<canvas id="myCanvas" width =getWidth() height=800>
What is the correct syntax to do it? Because what I'm doing doesn't work.
Solution 1:[1]
You can set the width like this :
function draw() {
var ctx = (a canvas context);
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
//...drawing code...
}
Solution 2:[2]
function setWidth(width) {
var canvas = document.getElementById("myCanvas");
canvas.width = width;
}
Solution 3:[3]
Try this:
var setCanvasSize = function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
Solution 4:[4]
To set the width and height of canvas you can use width and height object property of canvas to set width & height.
HTML - CODE
<canvas id="canvas"></canvas>
Javscript
const canvas = document.getElementById('canvas')
canvas.width = 300 // 300px
canvas.height = 200 //200px
const canvas = document.getElementById('canvas')
canvas.width = 350
canvas.height = 200
#canvas {
background-color:blue
}
<canvas id="canvas"></canvas>
Solution 5:[5]
Try this:
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
xS = w.innerWidth || e.clientWidth || g.clientWidth,
yS = w.innerHeight|| e.clientHeight|| g.clientHeight;
alert(xS + ' × ' + yS);
document.write('')
works for iframe and well.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Luc CR |
| Solution 2 | |
| Solution 3 | Forgot Vegas Hero |
| Solution 4 | Muneeb Ejaz |
| Solution 5 | OpenRobotix.Com |
