悟夕导航

把画布撸得飞起:HTML5 Canvas 极速上手

55 0 0
不用装 PS,也不用开 AE,浏览器里就能画图、做动画,甚至跑小游戏——秘诀就是一块 <canvas>。下面这 篇“现学现卖”笔记,从 0 到 1 带你画出色块、圆球、会跑的小球,全程复制即可运行。

1 先把画布支起来

<canvas id="c" width="500" height="400"></canvas>
<script src="draw.js"></script>

就这么简单:给宽高、写 ID,剩下的交给 JS。
(注意:别用 CSS 硬拉大小,否则图形会变形。)


2 拿“画笔”——2D 上下文

// draw.js
const c = document.getElementById('c');
const ctx = c.getContext('2d');   // 画笔到手

以后所有“画什么、怎么画”都靠 ctx 这个对象说话。


3 画点真东西

① 矩形(实心 / 空心)

ctx.fillStyle = 'royalblue';
ctx.fillRect(50, 50, 150, 100);      // 实心

ctx.strokeStyle = 'tomato';
ctx.lineWidth = 4;
ctx.strokeRect(50, 50, 150, 100);    // 描边

② 圆

ctx.beginPath();                     // 新路径
ctx.arc(300, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = 'seagreen';
ctx.fill();
ctx.stroke();                        // 顺手描个边

③ 直线

ctx.beginPath();
ctx.moveTo(50, 200);                 // 起点
ctx.lineTo(200, 300);                // 终点
ctx.strokeStyle = 'purple';
ctx.lineWidth = 5;
ctx.stroke();

4 写字也能“写”

ctx.font = '24px sans-serif';
ctx.fillStyle = '#333';
ctx.fillText('Hello Canvas', 50, 350);

5 让圆跑起来——最简动画

思路就是:擦 → 画 → 挪 → 循环。

let x = 0;
function loop() {
  ctx.clearRect(0, 0, c.width, c.height); // 擦掉
  ctx.beginPath();
  ctx.arc(x, 200, 30, 0, Math.PI * 2);
  ctx.fillStyle = 'dodgerblue';
  ctx.fill();
  x += 2;                                 // 挪
  if (x > c.width) x = 0;                 // 到头回弹
  requestAnimationFrame(loop);            // 循环
}
loop();                                   // 开跑

6 跟鼠标互动——点哪画哪

c.addEventListener('click', e => {
  const rect = c.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;
  ctx.fillStyle = 'crimson';
  ctx.beginPath();
  ctx.arc(x, y, 8, 0, Math.PI * 2);
  ctx.fill();
});

7 常用 API 速查(收藏不亏)

功能关键代码
颜色 / 描边fillStyle / strokeStyle
线粗lineWidth = 数值
画矩形fillRect(x,y,w,h)
画圆arc(x,y,r,0,Math.PI*2)
写字fillText(text,x,y)
清屏clearRect(0,0,画布宽,画布高)
动画循环requestAnimationFrame(函数)

8 进阶指个路

  • 想画曲线?玩 quadraticCurveTo / bezierCurveTo
  • 要贴图?drawImage(img, x, y)
  • 做粒子、物理?上 OffscreenCanvas + 双缓冲
  • 图例、图表?别重复造轮子,echarts、Chart.js 都基于 Canvas

9 打包带走

把最上面 HTML 和 JS 片段拼一起,双击即可跑。
下一步,换颜色、改坐标、加交互,全是你的创意——画布已经备好,剩下的就是“把像素当成乐高”。

祝撸码愉快,让浏览器替你画画!

0
快来点个赞吧

发表评论

隐私评论

评论列表

来写一个评论吧