73

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.

Anish Gupta
  • 2,200
  • 2
  • 22
  • 37
Kerry
  • 955
  • 1
  • 8
  • 11

6 Answers6

77

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...
}
Luc CR
  • 1,006
  • 6
  • 10
42
function setWidth(width) {
  var canvas = document.getElementById("myCanvas");  
  canvas.width = width;
}
bozdoz
  • 11,847
  • 7
  • 63
  • 92
13

Try this:

var setCanvasSize = function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
2

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>
Muneeb Ejaz
  • 82
  • 1
  • 6
1

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.

-10

You can also use this script , just change the height and width

<canvas id="Canvas01" width="500" height="400" style="border:2px solid #FF9933; margin-left:10px; margin-top:10px;"></canvas>

   <script>
      var canvas = document.getElementById("Canvas01");
      var ctx = canvas.getContext("2d");
Supriadi
  • 1
  • 1
  • 1
    OP has evidently gotten this far already. I think he/she wants to resize the canvas in the JS code. – adrian Oct 14 '18 at 00:10