Dynamic canvas width and height

From what I understand about canvas,

  • Identify a board with size
  • Then we can only draw it

But I'm trying to reach

  • Draw text
  • Measure text size
  • Determine Canvas Size

HTML

<div style="background:grey;display:inline-block;">
   <canvas id="samplecanvas" style="background:red;"></canvas>
</div>

Javascript

var c = document.getElementById("samplecanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World" ,10, 50);

Is there a way to measure the size of the text and dynamically adjust the size of the canvas?

This is my demonstration, I define a canvas without any size and draw on it, but the canvas is large and has a lot of extra space. I am trying to make div div and canvas match content size

http://jsfiddle.net/5877a4aq/2/

+4
source share
2 answers

, , , .

, measureText(), reset (). , reset , .

var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

function drawTextAndResize(text, fontSize, font){
  text = text || "hello world";
  fontSize =  fontSize || 48;
  font = font || "serif";
  // First we set the font to the context
  ctx.font = fontSize + 'px '+ font;
  // We set the size of our canvas accordingly to the width of our text
  canvas.width = ctx.measureText(text).width;
  // 1.3*fontSize is an approximation of the line height, for a complete way to get the height, refer to this answer : http://stackoverflow.com/a/17631567/3702797
  canvas.height = fontSize*1.3;
  // Since our context has been reset, we have to reset its font as well
  ctx.font = fontSize + 'px '+ font;
  // Finally we draw the text, approximately vertically centered
  ctx.fillText(text, 0,canvas.height/1.3);
  }

drawTextAndResize("This is some text", 32, "arial");
setTimeout(drawTextAndResize, 4000);
canvas{border:1px solid}
<canvas/>
Hide result
+2

:

1

ctx.fillText(<text>, <pos-x>, <pos-y>);

2:

var x = ctx.measureText(<text>).width;

3:

ctx.canvas.width = x * <scale>;
ctx.canvas.height = x * <scale>;
-1

All Articles