10分钟学会HTML5 Canvas绘图,快速上手前端图形开发
本文面向前端开发初学者,系统讲解HTML5 Canvas绘图基础与进阶方法。内容涵盖Canvas基本使用、线条与形状绘制、颜色填充、渐变效果、文本绘制、图像加载及简单动画实现。通过实例讲解和分步操作,帮助读者快速掌握Canvas绘图技能,为网页交互和数据可视化提供基础。
正文教程
一、Canvas基础
<canvas id="myCanvas" width="400" height="300" style="border:1px solid #000;"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d'); // 获取2D绘图上下文
</script>
技巧:
getContext('2d')是绘制Canvas图形的核心
二、绘制矩形与线条
// 矩形
ctx.fillStyle = '#3498db'; // 填充颜色
ctx.fillRect(50, 50, 100, 50); // x, y, 宽, 高
// 线条
ctx.strokeStyle = '#e74c3c';
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(50,150);
ctx.lineTo(200,150);
ctx.stroke();
技巧:
fillRect用于填充矩形,stroke用于绘制线条
三、绘制圆形与弧线
ctx.beginPath();
ctx.arc(150, 100, 50, 0, Math.PI*2); // 圆心x, y, 半径, 起始角, 结束角
ctx.fillStyle = '#2ecc71';
ctx.fill();
ctx.strokeStyle = '#27ae60';
ctx.stroke();
技巧:
arc可绘制圆形和弧线,fill填充颜色,stroke绘制边框
四、渐变与颜色
// 线性渐变
const gradient = ctx.createLinearGradient(0,0,200,0);
gradient.addColorStop(0,'red');
gradient.addColorStop(1,'yellow');
ctx.fillStyle = gradient;
ctx.fillRect(50, 200, 200, 50);
技巧:
createLinearGradient创建线性渐变,可实现渐变填充效果
五、绘制文本
ctx.font = '20px Arial';
ctx.fillStyle = '#34495e';
ctx.fillText('Hello Canvas', 50, 50);
ctx.strokeStyle = '#e67e22';
ctx.strokeText('Outline Text', 50, 80);
技巧:
fillText绘制填充文本,strokeText绘制轮廓文本
六、绘制图像
const img = new Image();
img.src = 'https://via.placeholder.com/100';
img.onload = function() {
ctx.drawImage(img, 250, 50, 100, 100); // x, y, 宽, 高
}
技巧:
drawImage用于绘制图片,可实现缩放和位置调整
七、Canvas简单动画
let x = 0;
function animate() {
ctx.clearRect(0,0,canvas.width,canvas.height); // 清空画布
ctx.fillStyle = 'blue';
ctx.fillRect(x, 150, 50, 50);
x += 2;
if(x > canvas.width) x = -50;
requestAnimationFrame(animate); // 循环调用
}
animate();
技巧:使用
requestAnimationFrame实现平滑动画
八、实用技巧总结
先获取Canvas上下文,再进行绘图操作
常用绘图方法:
fillRect、stroke、arc、fillText、drawImagebeginPath和closePath管理绘图路径,避免路径叠加使用渐变和颜色填充提升视觉效果
利用
requestAnimationFrame实现高效动画