返回
canvas如何做款祝福月饼【中秋特别版】
前端
2023-11-27 16:46:49
1. 准备工作
- 安装Canvas库
- 准备一个画布
- 选择合适的颜色
- 确定月饼的大小和位置
2. 绘制月饼
- 使用beginPath()方法开始路径
- 使用arc()方法绘制圆形
- 使用closePath()方法关闭路径
- 使用fillStyle()方法设置填充颜色
- 使用fill()方法填充路径
3. 添加祝福语
- 使用font()方法设置字体
- 使用textAlign()方法设置文本对齐方式
- 使用fillText()方法写入祝福语
4. 添加动画
- 使用requestAnimationFrame()方法请求浏览器在屏幕刷新时调用指定的函数
- 在函数中更新月饼的位置或大小
- 重复步骤4以创建动画
5. 保存动画
- 使用toDataURL()方法将动画保存为图片
- 使用saveAs()方法将图片保存到本地
代码示例
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// 设置画布背景颜色
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制月饼
ctx.beginPath();
ctx.arc(250, 250, 100, 0, 2 * Math.PI);
ctx.closePath();
ctx.fillStyle = "#ff9900";
ctx.fill();
// 添加祝福语
ctx.font = "bold 30px Arial";
ctx.textAlign = "center";
ctx.fillStyle = "#000000";
ctx.fillText("中秋快乐", 250, 280);
// 添加动画
function animate() {
// 更新月饼的位置
x += 1;
y += 1;
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 重新绘制月饼
ctx.beginPath();
ctx.arc(x, y, 100, 0, 2 * Math.PI);
ctx.closePath();
ctx.fillStyle = "#ff9900";
ctx.fill();
// 添加祝福语
ctx.font = "bold 30px Arial";
ctx.textAlign = "center";
ctx.fillStyle = "#000000";
ctx.fillText("中秋快乐", x, y + 30);
// 请求浏览器在屏幕刷新时调用animate()函数
requestAnimationFrame(animate);
}
// 启动动画
animate();
// 保存动画
var image = canvas.toDataURL("image/png");
saveAs(image, "中秋祝福月饼.png");
</script>
中秋将至,赶快动手制作一款祝福月饼,送给自己,送亲人,送朋友!