0

I am using the following code (in accordance with this answer) to have a responsive canvas:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
ctx.font = '52px verdana';
var text = 'Sample text';
var textWidth = ctx.measureText(text).width;
ctx.fillText(text, 50, 50);
canvas {
  width: 100%;
  height: auto;
}
<div class="container">
  <div class="row">
    <div class="col-md-12">
      <canvas id="canvas" width="800">
        Sorry, your browser doesn't support the &lt;canvas&gt; element.
      </canvas>
    </div>
  </div>
</div>

It doesn't look well because the actual canvas element size is not 800, but 1140 (in my browser). Looks like I should detect the window size somehow and assign correct canvas size value. How should I do it? I am using the latest Twitter Bootstrap library.

Community
  • 1
  • 1
LA_
  • 18,018
  • 53
  • 160
  • 288
  • The canvas width attribute is different from the canvas' style width. See: [Size of HTML5 Canvas via CSS versus element attributes](http://stackoverflow.com/questions/5034529/size-of-html5-canvas-via-css-versus-element-attributes) and [HTML5 Canvas 100% Width Height of Viewport?](http://stackoverflow.com/a/8486324/1762224) – Mr. Polywhirl Jan 13 '15 at 16:34

1 Answers1

1

Dont use css style

ctx.canvas.width  = window.innerWidth || document.body.clientWidth;