Canvas之绘制字符串

上篇我们我们已经了解完了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()

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

猜你喜欢

转载自blog.csdn.net/Efficiency9/article/details/75007838