2

I have seen various answers on canvas resize but could not understand the problem I am facing. Following is the canvas element rendered on my web app.

Before Rendering: 

    <canvas id="g_5" resize></canvas>

After Rendering:

     <canvas id="g_5"  resize width="1076" height="306" style="-webkit-user-select: none; touch-action: none; -webkit-user-drag: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); width: 1148.38px; height: 300px;"></canvas>  

I am setting height and width of canvas as follows:

        var canvas = document.getElementById(canvasId);
        var context = canvas.getContext('2d');
        var width = <someWidth>;  //=1076 in this case
        var height = <someHeight>; //=306 in this case
        canvas.width = width;
        canvas.height = height;

After doing this, width/height in style supersedes the attribute width/height and hence canvas uses style's height/width.

My questions are:

  1. Why there are two different width/height?
  2. How to set them to have same value
  3. If I remove resize attribute from canvas element, canvas size stays to default size.
Aman Gupta
  • 3,627
  • 4
  • 40
  • 64

1 Answers1

1
  1. Setting width/height in html attributes is being applied first until the css is loaded.
  2. After css is loaded the width/height attributes is ignored and use its style definition.
  3. After using the javascript resize code then you'll get the canvas resized in that event.
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231