ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

javascript – 动态画布宽度和高度

2019-07-02 19:19:48  阅读:217  来源: 互联网

标签:javascript css html5 canvas html


根据我对画布的理解,

>定义尺寸的电路板
>那我们只能借鉴它

但我正在努力实现

>画出文字
>测量文字大小
>定义画布大小

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/

解决方法:

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

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

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 : https://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/>

标签:javascript,css,html5,canvas,html
来源: https://codeday.me/bug/20190702/1359209.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有