在 JS 中使用 canvas 绘制文字边框
实现说明:
先使用 CanvasRenderingContext2D 对象的 fillText() 绘制文字,再使用 strokeText() 绘制文字边框。 下面展示了详细用法
效果展示:
tip: 不同字体的边框效果会存在一些差异
实现代码:
html
<canvas id="canvas" width='300' height="90"></canvas>
javascript
// 创建画布
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
// 字体样式(粗细;大小;字体)
ctx.font = 'bold 72px "local_ygzd"';
ctx.fillStyle = "#54a8eB"; // 文字颜色为蓝色
ctx.fillText("阳光知道",0,72); //绘制文字
ctx.lineWidth = 3; //边框粗细
ctx.strokeStyle = "#F7DC6F"; // 淡黄色边框
ctx.strokeText("阳光知道",0,72); //绘制边框
代码说明:
其中变量 ctx 为一个 CanvasRenderingContext2D对象,我们用到它的以下属性与函数:
font与fillStyle用来设置设置字体样式与颜色fillText()在画布上绘制文字lineWidth设置边框粗细strokeStyle设置边框的颜色strokeText()在画布上绘制文字边框
版权声明:[自由转载-注明出处-非商用-非衍生] (知识共享许可协议)