Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the style size of a canvas dynamically by JavaScript? [duplicate]

The size (width and height) of a canvas can be changed, but the style size of the canvas can not be changed dynamically.

canvas = document.getElementById('test_fabric');
ctx = this.canvas.getContext('2d');
canvas.style.width = 1000;  // does not work.
canvas.style.height = 260;  // does not work.
canvas.width = 100;  // works.
canvas.height = 100;  // works.

Both canvas.width and canvas.height work well, but both canvas.style.width and canvas.style.height do not work.

In my case, the style size of the canvas only can be changed by a css file or inline style of the canvas.

canvas#test_fabric {
  width:400px;
  height:400px;
  background:gold;
}

or

<div><canvas id="test_fabric" width="200" height="200" 
style="width:200px; height:200px"></canvas></div>

Note: The css file becomes ineffective when the inline style exists.

What's the way to change the style size of a canvas dynamically by JavaScript?

like image 738
Calvin Avatar asked Feb 08 '16 11:02

Calvin


People also ask

How do you dynamically resize canvas?

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 .

How do you change the canvas size in HTML?

The default size for both element and drawing surface is 300 x 150 screen pixels. To set the height and width canvas HTML5 has two attributes: Height: With the help of Height attribute we can set the height. Width: With the help of Width attribute we can set the width.

How do I clear my HTML canvas?

To clear the Canvas, you can use the clearRect() method. This method performs pretty well than others for clearing the canvas (such as resetting the width/height, destroying the canvas element and then recreating it, etc..) const context = canvas. getContext('2d'); context.


1 Answers

The style properties' width and height requires the measurement for its values while html attributes' width and height does not require. So, you need to set px, em or % etc. explicitly in your code:

canvas = document.getElementById('test_fabric');
ctx = canvas.getContext('2d');
canvas.style.width = '1000px'; // explicitly setting its unit 'px'
canvas.style.height = '260px';

style.width/height without unit is invalid rule for css.

like image 84
Bhojendra Rauniyar Avatar answered Sep 19 '22 11:09

Bhojendra Rauniyar