Canvas API指南
设置与基本绘制
const canvas = document.querySelector('#myCanvas');
const ctx = canvas.getContext('2d');
// 设置画布尺寸(避免 CSS 拉伸)
canvas.width = 800;
canvas.height = 600;
// 矩形
ctx.fillStyle = '#6c63ff';
ctx.fillRect(50, 50, 200, 100); // x, y, 宽, 高
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
ctx.strokeRect(50, 50, 200, 100);
ctx.clearRect(60, 60, 30, 30); // 清除区域
// 圆形
ctx.beginPath();
ctx.arc(300, 150, 50, 0, Math.PI * 2);
ctx.fillStyle = '#ff6363';
ctx.fill();
路径
// 折线路径
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(200, 200);
ctx.lineTo(300, 100);
ctx.closePath();
ctx.stroke();
// 贝塞尔曲线
ctx.beginPath();
ctx.moveTo(50, 200);
ctx.bezierCurveTo(100, 100, 200, 100, 250, 200);
ctx.stroke();
// 圆角矩形
ctx.beginPath();
ctx.roundRect(50, 50, 200, 100, 12);
ctx.fill();
文字
ctx.font = 'bold 24px PingFang SC, sans-serif';
ctx.fillStyle = '#ffffff';
ctx.textAlign = 'center'; // left | right | center | start | end
ctx.textBaseline = 'middle'; // top | middle | bottom | alphabetic
ctx.fillText('你好,Canvas', 400, 300);
ctx.strokeText('描边文字', 400, 350);
// 测量文字宽度
const metrics = ctx.measureText('你好');
console.log(metrics.width); // 像素宽度
变换与渐变
// 保存/恢复状态
ctx.save();
ctx.translate(400, 300); // 移动原点
ctx.rotate(Math.PI / 4); // 旋转 45 度
ctx.scale(2, 2);
ctx.fillRect(-50, -50, 100, 100);
ctx.restore();
// 线性渐变
const grad = ctx.createLinearGradient(0, 0, 400, 0);
grad.addColorStop(0, '#6c63ff');
grad.addColorStop(1, '#ff6363');
ctx.fillStyle = grad;
ctx.fillRect(0, 0, 400, 100);
动画循环
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#6c63ff';
ctx.beginPath();
ctx.arc(x, 200, 30, 0, Math.PI * 2);
ctx.fill();
x = (x + 2) % canvas.width;
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);