Z
ZHANK
多媒体

Canvas 画布入门

canvas 元素、2D 上下文、绘制矩形/圆形/线条/文字/渐变

Canvas 画布入门

<canvas> 提供了一块可编程绘图区——用 JavaScript 在上面画图、做动画、开发游戏。

学完本章你将: 掌握 canvas 元素、获取 2D 上下文、绘制基本图形。


基础模板

html
<canvas id="myCanvas" width="400" height="200"
        style="border: 1px solid #ccc;">
  你的浏览器不支持 Canvas。
</canvas>

<script>
  const canvas = document.getElementById("myCanvas");
  const ctx = canvas.getContext("2d");
</script>

绘制基本图形

javascript
// 矩形
ctx.fillStyle = "tomato";
ctx.fillRect(20, 20, 100, 60);        // 填充矩形

ctx.strokeStyle = "blue";
ctx.lineWidth = 3;
ctx.strokeRect(150, 20, 100, 60);     // 描边矩形

ctx.clearRect(60, 40, 20, 20);        // 清除(擦除)

// 圆形
ctx.beginPath();
ctx.arc(300, 80, 40, 0, 2 * Math.PI);
ctx.fillStyle = "gold";
ctx.fill();
ctx.stroke();

// 线条
ctx.beginPath();
ctx.moveTo(20, 130);
ctx.lineTo(200, 180);
ctx.lineTo(380, 140);
ctx.strokeStyle = "green";
ctx.stroke();

绘制文字

javascript
ctx.font = "24px Arial";
ctx.fillStyle = "#333";
ctx.fillText("Hello Canvas!", 50, 50);

ctx.font = "bold 30px 微软雅黑";
ctx.strokeStyle = "red";
ctx.strokeText("描边文字", 50, 100);