Calvin February 2016

How to change the style size of a canvas dynamicly by JavaScript?

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 dynamicly by JavaScript?

Thanks in advance!

Answers


Bhojendra Nepal February 2016

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.


abhay vyas February 2016

i have used jquery that use css method for height and width setting

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript">
       $(document).ready(function(){
        $("#test_fabric").css({"border-color": "#C1E0FF", 
                 "border-width":"1px", 
                 "border-style":"solid","height":"500px","width":"500px"});
       });
    </script>
    <div class="col-md-12">
        <div><canvas id="test_fabric" width="200" height="200"></canvas></div>
    </div>

Post Status

Asked in February 2016
Viewed 2,358 times
Voted 9
Answered 2 times

Search




Leave an answer