78

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,218
  • 2
  • 23
  • 37
Kerry
  • 1,015
  • 1
  • 9
  • 11

6 Answers6

84

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,086
  • 6
  • 11
48
function setWidth(width) {
  var canvas = document.getElementById("myCanvas");  
  canvas.width = width;
}
bozdoz
  • 12,550
  • 7
  • 67
  • 96
14

Try this:

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

To set the width and height of canvas you can use width and height object property of canvas to set width & height.

const canvas = document.getElementById('canvas')
canvas.width = 350     // 350px
canvas.height = 200    // 200px
#canvas {
    background-color:blue
}
<canvas id="canvas"></canvas>
shA.t
  • 16,580
  • 5
  • 54
  • 111
Muneeb Ejaz
  • 696
  • 6
  • 11
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