# 代码复用

# 封装函数

// 封装的一个用于绘制圆角矩形的函数.
function roundedRect(ctx, x, y, width, height, radius) {
  ctx.beginPath();
  ctx.moveTo(x, y + radius);
  ctx.lineTo(x, y + height - radius);
  ctx.quadraticCurveTo(x, y + height, x + radius, y + height);
  ctx.lineTo(x + width - radius, y + height);
  ctx.quadraticCurveTo(x + width, y + height, x + width, y + height - radius);
  ctx.lineTo(x + width, y + radius);
  ctx.quadraticCurveTo(x + width, y, x + width - radius, y);
  ctx.lineTo(x + radius, y);
  ctx.quadraticCurveTo(x, y, x, y + radius);
  ctx.stroke();
}
function draw() {
  const canvas = document.getElementById("demo5_1");
  canvas.width = 200;
  canvas.height = 200;
  if (canvas.getContext) {
    const ctx = canvas.getContext("2d");
    roundedRect(ctx, 10, 10, 180, 180, 20, 20);
  }
}
draw();

# 路径对象 Path2D()

Path2D()会返回一个新初始化的 Path2D 对象 Path2D.addPath(path[, transform])添加一条路径到当前路径

let path = new Path2D(); // 空的Path对象
let newPath = new Path2D(path); // 克隆Path对象
let pathFormSVG = new Path2D(d); // 从一个SVG创建

看代码

function draw() {
  const canvas = document.getElementById("demo5_2");
  canvas.width = 300;
  canvas.height = 200;
  if (canvas.getContext) {
    const ctx = canvas.getContext("2d");
    const rectangle = new Path2D();
    rectangle.rect(10, 10, 50, 50);
    const circle = new Path2D();
    circle.moveTo(125, 35);
    circle.arc(100, 35, 25, 0, 2 * Math.PI);
    ctx.stroke(rectangle);
    ctx.fill(circle);
    const ellipse = new Path2D(
      "M 110 120, C 110 140 ,190 140, 190  120  C 190 100, 110 100 ,110 120  Z"
    );
    ctx.stroke(ellipse);
  }
}
draw();

看效果

# 图章 Patterns

玩过 scratch 和 Adboe Acrobat DC 的小伙伴可能知道有一个绘图工具叫做图章,图章代表了一个可被重复使用的图形,或者由一组绘画命令组成的整体图形。

在Canvas中使用createPattern(image,type)来创建一个图章,其来源可以是一个Image对象的引用,或者另一个canvas对象,type必须是以下字符串之一:repeat,repeat-x,repeat-y 和 no-repeat,类似于 CSS 中的 background-repeat

看代码

function draw() {
  const canvas = document.getElementById("demo5_3");
  canvas.width = canvas.height = 300;
  const ctx = canvas.getContext("2d");
  const img = new Image();
  img.src = "https://static.gausszhou.top/data/image/learn/canvas/canvas_createpattern.png";
  img.onload = function () {
    const pattern = ctx.createPattern(img, "repeat");
    ctx.fillStyle = pattern;
    ctx.fillRect(0, 0, 300, 300);
  };
}
draw();

看效果