Set Canvas size using javascript

JavascriptHtmlCanvas

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

function setWidth(width) {
  var canvas = document.getElementById("myCanvas");  
  canvas.width = width;
}

Solution 3 - Javascript

Try this:

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

Solution 4 - Javascript

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 - Javascript

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.

Solution 6 - Javascript

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");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKerryView Question on Stackoverflow
Solution 1 - JavascriptLuc CRView Answer on Stackoverflow
Solution 2 - JavascriptbozdozView Answer on Stackoverflow
Solution 3 - JavascriptForgot Vegas HeroView Answer on Stackoverflow
Solution 4 - JavascriptMuneeb EjazView Answer on Stackoverflow
Solution 5 - JavascriptOpenRobotix.ComView Answer on Stackoverflow
Solution 6 - JavascriptSupriadiView Answer on Stackoverflow