https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript/Client-side_web_APIs/Drawing_graphics
画布上下文:var ctx = canvas.getContext(‘2d’);

2D 画布基础

画布左上角的坐标是(0, 0),横坐标(x)轴向右延伸,纵坐标(y)轴向下延伸。
canvas - 图1

  1. ctx.fillStyle = 'rgb(255, 0, 0)';
  2. ctx.fillRect(50, 50, 100, 150);

左边和顶边与画布边缘距离均为 50 像素(由前两个参数指定),宽 100 像素、高 150 像素(由后两个参数指定)。

  1. var canvas = document.querySelector('.myCanvas');
  2. var width = canvas.width = window.innerWidth;
  3. var height = canvas.height = window.innerHeight;
  4. var ctx = canvas.getContext('2d');
  5. ctx.fillStyle = 'rgb(0, 0, 0)';
  6. ctx.fillRect(0, 0, width, height);
  7. ctx.fillStyle = 'rgb(255, 0, 0)';
  8. ctx.fillRect(50, 50, 100, 150);
  9. ctx.fillStyle = 'rgba(0, 255, 0,.5)';
  10. ctx.fillRect(75, 75, 100, 100);
  11. ctx.strokeStyle = 'rgb(255, 255, 255)';
  12. ctx.strokeRect(25, 25, 175, 200);
  13. ctx.lineWidth = 5;

矩形:

  1. ctx.fillStyle = 'rgb(0, 255, 0)';
  2. ctx.fillRect(75, 75, 100, 100);

描边类似于border

  1. 在上文的 JS 代码的末尾添加以下代码:

    1. ctx.strokeStyle = 'rgb(255, 255, 255)';
    2. ctx.strokeRect(25, 25, 175, 200);
  2. 默认的描边宽度是 1 像素,可以通过调整 lineWidth 属性(接受一个表示描边宽度像素值的数字)的值来修改。在上文两行后添加以下代码:

    1. ctx.lineWidth = 5;

    绘制路径

  • beginPath():在钢笔当前所在位置开始绘制一条路径。在新的画布中,钢笔起始位置为 (0, 0)。
  • moveTo():将钢笔移动至另一个坐标点,不记录、不留痕迹,只将钢笔“跳”至新位置。
  • fill():通过为当前所绘制路径的区域填充颜色来绘制一个新的填充形状。
  • stroke():通过为当前绘制路径的区域描边,来绘制一个只有边框的形状。