创建 canvas 画布
注意:
- canvas 的原点是在左上角,而不是传统的左下角,这个需要自己处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title>
<style> #canvas { width: 100vw; height: 100vh; } </style> </head>
<body> <canvas id="canvas"></canvas>
<script> const $canvas = document.getElementById("canvas");
$canvas.width = $canvas.offsetWidth; $canvas.height = $canvas.offsetHeight;
const ctx = $canvas.getContext("2d");
</script> </body> </html>
|
基础图形的绘制
图形的绘制基本都包含 路径绘制 stroke 和 颜色填充 fill。
视业务需要灵活选择。
折线
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
ctx.beginPath(); ctx.strokeStyle = "red"; ctx.lineWidth = 5; ctx.setLineDash([10, 5]); ctx.moveTo(0, 0); ctx.lineTo(100, 100); ctx.lineTo(200, 0); ctx.closePath(); ctx.stroke();
ctx.fillStyle = "blue"; ctx.fill();
|
矩形
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| ctx.beginPath(); ctx.strokeStyle = "red"; ctx.setLineDash([10, 0]); ctx.lineWidth = 5; ctx.strokeRect(50, 50, 200, 100);
ctx.fillStyle = "blue"; ctx.fillRect(50, 50, 200, 100);
ctx.clearRect(75, 75, 100, 50);
|
圆形
1 2 3 4 5 6 7 8 9 10 11 12
| const radius = 50; ctx.beginPath(); ctx.strokeStyle = "red"; ctx.setLineDash([10, 0]); ctx.lineWidth = 5; ctx.arc(300, 300, radius, 0, Math.PI * 2, false); ctx.stroke();
ctx.fillStyle = "blue"; ctx.fill();
|
剪切图形
有时候需要在一个异形区域类绘制图形,此时就需要裁剪功能 clip() 了
1 2 3 4 5 6 7 8 9 10 11 12 13
| ctx.beginPath(); ctx.moveTo(500, 500); ctx.lineTo(500, 500); ctx.lineTo(550, 550); ctx.lineTo(520, 600); ctx.closePath(); ctx.clip();
ctx.fillStyle = "green"; ctx.fill();
|
存档和回档
1 2 3 4 5 6 7 8 9 10 11
|
ctx.save();
ctx.restore();
|
参考
Canvas 绘制虚线 setLineDash 方法说明