canvas是基于状态绘制的,每次平移、旋转、缩放、矩阵等变换之前,先调用save()保存当前绘图状态,变换结束之后,若要继续使用变换之前的状态,调用restore()方法即可。
效果图:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#cvs {
background-color: #ccc;
}
</style>
</head>
<body>
<div id='container'>
<canvas id='cvs'>
sorry, your browser doesn't support canvas API.
</canvas>
</div>
</body>
<script>
window.onload = function() {
// 获取画布
const cvs = document.querySelector('#cvs')
cvs.width = 800
cvs.height = 600
// 获取画笔
const ctx = cvs.getContext('2d')
for(let i = 0; i < 11; i++) {
ctx.save()
ctx.translate(400, 300)
ctx.rotate(36 * i * Math.PI / 180)
ctx.bezierCurveTo(30, 50, 350, 550, 100, 150)
ctx.fillStyle = 'rgba(255, 0, 255, 0.25)'
ctx.fill()
ctx.restore()
}
}
</script>
</html>