第 5 课 4 / 19 | 编码:L05-07
核心知识

坐标系与 2D 上下文

把画布左上角看作原点 (0, 0):向右移动,x 增大;向下移动,y 增大。ctx 指向二维绘图上下文对象,调用 ctx.fillRect(...) 就可以在对应的画布上绘制矩形。

<style>
body {
  font: 20px/1.5 sans-serif;
  padding: 16px;
  color: #20354e;
}
button, input, select { font: inherit; }

</style>
<canvas id="poster" width="640" height="360" style="max-width:100%;height:auto;border:1px solid #aaa">黄梅戏分享会海报</canvas>
<script>
const canvas = document.querySelector('#poster');
const ctx = canvas.getContext('2d');
console.log('画布宽高:', canvas.width, canvas.height);
ctx.fillRect(10, 10, 30, 30);
</script>