前端技术探索系列:HTML5 Canvas 绘图详解 🎨
开篇寄语 👋
前端开发者们,
在前四篇文章中,我们探讨了 HTML5 的各种特性。今天,让我们一起探索 Canvas 的神奇世界,看看如何用代码创造出绚丽的视觉效果。
一、Canvas 基础入门 🖌️
1. 创建 Canvas 环境
<canvas id="myCanvas" width="800" height="600">
您的浏览器不支持 Canvas 元素
</canvas>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 设置画布尺寸为设备像素比
function setCanvasSize() {
const dpr = window.devicePixelRatio || 1;
canvas.width = canvas.clientWidth * dpr;
canvas.height = canvas.clientHeight * dpr;
ctx.scale(dpr, dpr);
}
2. 基础图形绘制 ⭐
class CanvasDrawing {
constructor(ctx) {
this.ctx = ctx;
}
// 矩形
drawRect(x, y, width, height, style = '#000') {
this.ctx.fillStyle = style;
this.ctx.fillRect(x, y, width, height);
}
// 圆形
drawCircle(x, y, radius, style = '#000') {
this.ctx.beginPath();
this.ctx.arc(x, y, radius, 0, Math.PI * 2);
this.ctx.fillStyle = style;
this.ctx.fill();
}
// 线条
drawLine(startX, startY, endX, endY, style = '#000', width = 1) {
this.ctx.beginPath();
this.ctx.moveTo(startX, startY);
this.ctx.lineTo(endX, endY);
this.ctx.strokeStyle = style;
this.ctx.lineWidth = width;
this.ctx.stroke();
}
// 文本
drawText(text, x, y, style = '#000', font = '16px Arial') {
this.ctx.font = font;
this.ctx.fillStyle = style;
this.ctx.fillText(text, x, y);
}
}
3. 路径与形状 ✨
class PathDrawing {
constructor(ctx) {
this.ctx = ctx;
}
// 绘制多边形
drawPolygon(points, style = '#000', fill = true) {
this.ctx.beginPath();
this.ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) {
this.ctx.lineTo(points[i].x, points[i].y);
}
this.ctx.closePath();
if (fill) {
this.ctx.fillStyle = style;
this.ctx.fill();
} else {
this.ctx.strokeStyle = style;
this.ctx.stroke();
}
}
// 贝塞尔曲线
drawCurve(startX