HTML5 Canvas 完整教程
Canvas 是 HTML5 最强大的特性之一,提供可绘图的画布区域,通过 JavaScript 可以创建精美的 2D 图形、图表和动画。
什么是 Canvas
<canvas> 是 HTML5 新增的元素,专门用于图形绘制。Canvas 是通过 JavaScript 动态渲染的,非常适合创建:
- 交互式图表和数据可视化
- 网页游戏和动画
- 图像处理和滤镜效果
- 签名板和绘图应用
Canvas 基础
创建 Canvas
canvas基础结构
<canvas id="myCanvas" width="800" height="600">
您的浏览器不支持 Canvas
</canvas>
获取上下文
获取 Canvas 上下文
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
绘制矩形
绘制矩形
// 填充矩形
ctx.fillStyle = "#FF0000";
ctx.fillRect(10, 10, 150, 100);
// 描边矩形
ctx.strokeStyle = "#0000FF";
ctx.lineWidth = 3;
ctx.strokeRect(200, 30, 120, 80);
// 清除区域
ctx.clearRect(0, 0, canvas.width, canvas.height);
路径绘制
绘制圆形和弧线
// 绘制圆形
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = "#FF0000";
ctx.fill();
// 绘制直线
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(200, 150);
ctx.strokeStyle = "#00FF00";
ctx.stroke();
// 绘制三角形
ctx.beginPath();
ctx.moveTo(300, 100);
ctx.lineTo(350, 180);
ctx.lineTo(250, 180);
ctx.closePath();
ctx.fillStyle = "steelblue";
ctx.fill();
贝塞尔曲线
贝塞尔曲线示例
// 二次贝塞尔曲线
ctx.beginPath();
ctx.moveTo(50, 200);
ctx.quadraticCurveTo(150, 50, 250, 200);
ctx.stroke();
// 三次贝塞尔曲线(波浪形)
ctx.beginPath();
ctx.moveTo(50, 150);
ctx.bezierCurveTo(150, 50, 250, 250, 350, 150);
ctx.stroke();
绘制文本
文本绘制示例
// 设置字体
ctx.font = "30px Arial";
// 填充文本
ctx.fillStyle = "#FF0000";
ctx.fillText("Hello World!", 50, 50);
// 文本对齐
ctx.textAlign = "center";
ctx.fillText("居中文字", canvas.width / 2, 100);
渐变填充
渐变示例
// 线性渐变
var gradient = ctx.createLinearGradient(0, 0, 400, 0);
gradient.addColorStop(0, "#FF0000");
gradient.addColorStop(0.5, "#00FF00");
gradient.addColorStop(1, "#0000FF");
ctx.fillStyle = gradient;
ctx.fillRect(10, 10, 380, 100);
// 径向渐变(球体效果)
var ballGradient = ctx.createRadialGradient(100, 100, 5, 100, 100, 50);
ballGradient.addColorStop(0, "#FFFFFF");
ballGradient.addColorStop(0.3, "#87CEEB");
ballGradient.addColorStop(1, "#4169E1");
ctx.fillStyle = ballGradient;
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.fill();
图形变换
变换示例
// 平移
ctx.save();
ctx.translate(100, 100);
ctx.fillRect(0, 0, 100, 50);
ctx.restore();
// 旋转
ctx.save();
ctx.translate(200, 150);
ctx.rotate(Math.PI / 4);
ctx.fillRect(-50, -25, 100, 50);
ctx.restore();
// 缩放
ctx.save();
ctx.scale(2, 2);
ctx.fillRect(200, 10, 50, 50);
ctx.restore();
动画实现
动画循环示例
var x = 0;
var speed = 2;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
x += speed;
if (x > canvas.width || x < 0) {
speed = -speed;
}
ctx.beginPath();
ctx.arc(x, 100, 30, 0, Math.PI * 2);
ctx.fillStyle = "#FF0000";
ctx.fill();
requestAnimationFrame(animate);
}
animate();
常见问题
Canvas 和 SVG 有什么区别?
Canvas 是位图,适合大量对象和频繁重绘的场景(如游戏);SVG 是矢量技术,适合需要缩放和可访问性的场景。
Canvas 画布模糊怎么办?
Retina 屏幕需要按比例缩放:
解决 Retina 模糊
var dpr = window.devicePixelRatio || 1;
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
ctx.scale(dpr, dpr);
💻 在线代码编辑器
👁️ 预览效果