Canvas之绘制字符串

这篇博客介绍了在Canvas中绘制字符串的方法,包括使用fillText和strokeText填充和描边字符串,调整字体、对齐方式及阴影效果。通过设置textAlign、textBaseline、font属性来控制字符串样式,并提供了相关实例说明,强调了在绘制时设置颜色和阴影的注意事项。

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

上篇我们我们已经了解完了canvas绘制基本图形(除了圆形)的知识,这一篇我们将了解到canvas如何绘制字符串的方法。
在绘制字符串时也有两个属性
字符串属性
- fillText(String Text, float x, float y, [float maxWidth]) 填充字符串
- strokeText(String Text, float x, float y, [float maxWidth]) 绘制字符串边框

以上两个属性功能在于设置文字内容,文字位置,最大宽度,在设置颜色时我们依然要用到fillStyle()以及strokeStyle()

字符串对齐

  • textAlign 设置绘制字符串的水平对齐方式(start、end、left、right、center等)
  • textBaseAlign 设置绘制字符串的垂直对齐方式(top、hanging、middle、alphabetic、idecgraphic、bottom 等)

字符串大小等

  • font:粗细 大小 字体

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<div>
    <canvas id="canvas_1" width="1000" height="500" style="box-shadow: 0px 0px 20px black;">
        当前浏览器不支持 canvas
    </canvas>
</div>
</body>
<script type="text/javascript">
    // 获取 canvas 元素对应的 DOM 对象
    var canvas_1 = document.getElementById("canvas_1");
    // 获取在 canvas 上绘图的 canvasRenderingContent2D 对象
    var ctx = canvas_1.getContext("2d");
    ctx.fillStyle='#da346d'
    ctx.strokeStyle='#e2e'
    ctx.font='40px 微软雅黑'
    ctx.fillText('山上有座庙',0,200);
    ctx.strokeText('从前有座山',100,100)
</script>
</html>

为字符串设置阴影

shadowBlur 设置阴影的模糊程度。该值是一个浮点数,该数值越大,阴影的模糊程度也就越大。
shadowColor 设置阴影的颜色。
shadowOffsetX 设置阴影在 X 方向的偏移
shadowOffsetY 设置阴影在 Y 方向的偏移

原理和css中的box-shadow相同
实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<div>
    <canvas id="canvas_1" width="1000" height="500" style="box-shadow: 0px 0px 20px black;">
        当前浏览器不支持 canvas
    </canvas>
</div>
</body>
<script type="text/javascript">
    // 获取 canvas 元素对应的 DOM 对象
    var canvas_1 = document.getElementById("canvas_1");
    // 获取在 canvas 上绘图的 canvasRenderingContent2D 对象
    var ctx = canvas_1.getContext("2d");
//后边不加单位
    ctx.shadowOffsetX=0;
    ctx.shadowOffsetY=6;
    ctx.shadowColor='#ccc';
    ctx.shadowBlur=10;
    ctx.fillStyle='#da346d'
    ctx.strokeStyle='#e2e'
    ctx.font='40px 微软雅黑'
    ctx.fillText('山上有座庙',0,200);
    ctx.strokeText('从前有座山',100,100)
</script>
</html>

代码注意点

  • 凡是属性设置的元素都要加”
  • 阴影设置的大小不加单位,只有数字即可
  • 设置颜色时,颜色也要用”包裹起来
  • 绘制字符串时,一定是要先设置fillStyle()和strokeStyle(),再设置fillText()和strokeText()
  • strokeStyle()不能用到fillText()

本篇博客如有错误,欢迎指出改正

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值