Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 600
Kerry Avatar asked Feb 12 '12 18:02

Kerry


People also ask

How do I change the size of the canvas in HTML?

Resizing the canvas on the fly is quite easy. To do it, simply set the width and height properties of the Canvas object, and then redraw the canvas contents: Canvas . width = 600 ; Canvas .

Does canvas work with JavaScript?

<canvas> is an HTML element which can be used to draw graphics via scripting (usually JavaScript).

How do you measure the height and width of a canvas?

You can get the width and height of a canvas element simply by accessing those properties of the element. For example: var canvas = document. getElementById('mycanvas'); var width = canvas.


2 Answers

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... } 
like image 155
Luc CR Avatar answered Sep 22 '22 15:09

Luc CR


function setWidth(width) {   var canvas = document.getElementById("myCanvas");     canvas.width = width; } 
like image 40
bozdoz Avatar answered Sep 25 '22 15:09

bozdoz