88

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.

4

7 Answers 7

91

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...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Draw function is not best place for this code. Use onresize with no problems.
51
function setWidth(width) {
  var canvas = document.getElementById("myCanvas");  
  canvas.width = width;
}

1 Comment

In here, the width must be just one number, without unit. correct: "100", not correct: "100px"
14

Try this:

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

Comments

5

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>

Comments

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.

1 Comment

document.write('<canvas id="myCanvas" width="'+xS+'" height="'+yS+'" ></canvas>')
0

If you are using the Fabric library:

canvas = new fabric.Canvas("editor", {
    selection: true,
    uniScaleTransform: true,
    preserveObjectStacking: true,
    selectionKey: 'ctrlKey',
});   

canvas.setHeight(height);
canvas.setWidth(width);

Comments

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

1 Comment

OP has evidently gotten this far already. I think he/she wants to resize the canvas in the JS code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.