canvas可以绘制多种样式的文字效果:比如渐变,阴影,描边等效果,如下图:
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div>绘制文字学习</div>
<canvas id="myCanvas" width="600" height="800"></canvas>
<script>
const canvas = document.getElementById('myCanvas')
const ctx = canvas.getContext('2d')
// 绘制文字
ctx.font = '30px Arial'
ctx.fillStyle = 'red'
ctx.fillText('Hello World', 10, 50)
ctx.closePath()
// 描边文字
ctx.beginPath()
ctx.strokeStyle = 'blue'
ctx.lineWidth = 1
ctx.strokeText('Hello World', 10, 100)
ctx.closePath()
// 绘制阴影文字
ctx.beginPath()
ctx.shadowOffsetX = 10
ctx.shadowOffsetY = 10
ctx.shadowBlur = 10
ctx.shadowColor = 'rgba(0, 0, 0, 0.5)'
ctx.fillStyle = 'green'
ctx.fillText('Hello World', 10, 150)
ctx.closePath()
// 绘制渐变文字
ctx.beginPath()
var gradient = ctx.createLinearGradient(0, 0, 300, 150)
gradient.addColorStop(0, 'black')
gradient.addColorStop(0.5, 'white')
gradient.addColorStop(1, 'red')
ctx.fillStyle = gradient
ctx.fillText('Hello World', 10, 200)
ctx.closePath()
</script>
</body>
</html>