动态画布宽度和高度

时间:2015-07-04 17:57:49

标签: javascript html css html5 canvas

根据我对画布的理解,

  1. 定义尺寸为
  2. 的纸板
  3. 然后我们只能画它
  4. 但我正在努力实现

    1. 绘制文字
    2. 测量文字大小
    3. 定义画布大小
    4. 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);
      

      有没有办法测量文字大小并动态调整画布大小?

      这是我的演示,我定义了没有任何大小的画布并在其上绘制,但画布大小很大并且有许多额外的空白区域。我正在尝试使 div和画布相应地扩展到内容大小

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

2 个答案:

答案 0 :(得分:3)

所以这是一个执行此操作的函数,它使用行高的近似值,如果需要多行文本,则需要一些调整。

请注意,您不必在measureText()之前绘制文字,但是当您更改画布时#0;高度和宽度,其上下文将重置(清除)。因此,您需要重置其字体属性,然后绘制文本。

&#13;
&#13;
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);
&#13;
canvas{border:1px solid}
&#13;
<canvas/>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

仅供参考:

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>;