canvas font-size 属性

本文探讨了HTML5 Canvas中字体大小的限制问题,特别是当font-size小于14像素时,文字显示不再随设置缩小的现象。通过示例代码演示不同字体大小的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在H5中,canvas是其一个重要的亮点和特性。

其中canvas的font-size属性和css的完全不同,w3c中定义如下

font-size / line-height 规定字号和行高,以像素计。

是以像素来渲染字体的,所有当font-size小于某个值时(一般是14)就会出现,textt的字符串不会变小(因为已经无法减少像素的数目,来呈现字体了。)


例子如下:当字体大小为25时:

<!DOCTYPE html>
<html>
	<body>

		<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
			Your browser does not support the HTML5 canvas tag.
		</canvas>

		<script>
		console.log(this);
			var c=document.getElementById("myCanvas");
			var ctx=c.getContext("2d");

			ctx.font="25px Arial";
			ctx.textBaseline="top";
			ctx.fillStyle = "red";
			ctx.fillText("Hello World",0,0);
			
		</script>

	</body>
</html>
效果如下:


当字体大小为14时:

<!DOCTYPE html>
<html>
	<body>

		<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
			Your browser does not support the HTML5 canvas tag.
		</canvas>

		<script>
		console.log(this);
			var c=document.getElementById("myCanvas");
			var ctx=c.getContext("2d");

			ctx.font="14px Arial";
			ctx.textBaseline="top";
			ctx.fillStyle = "red";
			ctx.fillText("Hello World",0,0);
			
		</script>

	</body>
</html>
效果如下:


当字体大小为5时:

<!DOCTYPE html>
<html>
	<body>

		<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
			Your browser does not support the HTML5 canvas tag.
		</canvas>

		<script>
		console.log(this);
			var c=document.getElementById("myCanvas");
			var ctx=c.getContext("2d");

			ctx.font="5px Arial";
			ctx.textBaseline="top";
			ctx.fillStyle = "red";
			ctx.fillText("Hello World",0,0);
			
		</script>

	</body>
</html>
效果如下:


说明当将设置为font-size《=13左右时,canvas中的字符已经不再发生变化了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值