Path2D | 青训营笔记

268 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 二 天

1. Path2D 对象(这是一个实验中的功能)

Path2D()会返回一个新初始化的 Path2D 对象

new Path2D();     // 空的 Path 对象
new Path2D(path); // 克隆 Path 对象
new Path2D(d);    // 从 SVG 建立 Path 对象

1.1 创建和拷贝路径

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var path1 = new Path2D();
path1.rect(10, 10, 100,100);

var path2 = new Path2D(path1);
path2.moveTo(220, 60);
path2.arc(170, 60, 50, 0, 2 * Math.PI);

ctx.stroke(path2);

path1描述的是生成一个以(10,10)为坐标的边长为100正方形。

path2描述的是生成path1后,将笔触移动到(220,60)后,再生成一个以(170,60)为圆心的半径50的圆。

效果图如下:

1.2 SVG路径

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var p = new Path2D("M10 10 h 80 v 80 h -80 Z");
ctx.fill(p);

使用 SVG path data 创建一个 Path2D 路径。路径将会移动到点 (10 10) ,然后向右侧水平方向移动 80 个点 (h 80),然后在深度方向上向下 80 个点 (v 80),然后向左 80 个点 (h -80),最后回到起始点 (z)。

生成的是一个边长为80的正方形,图略。

1.3 例3

function draw() {
  var canvas = document.getElementById('canvas');
  if (canvas.getContext){
    var ctx = canvas.getContext('2d');

    var rectangle = new Path2D();
    rectangle.rect(10, 10, 50, 50);

    var circle = new Path2D();
    circle.moveTo(125, 35);
    circle.arc(100, 35, 25, 0, 2 * Math.PI);

    ctx.stroke(rectangle);
    ctx.fill(circle);
  }
}

rectangle生成一个以(10,10)为坐标的边长为50正方形。

circle生成一个以(100,35)为圆心的半径25的圆。

效果图如下:

Path2D.addPath(path [, transform])

添加了一条路径到当前路径(可能添加了一个变换矩阵)。

  • m.a(默认需为1) x轴拉长(>1)/缩短(<1)
    • m.a=0.5时

  • m.b(默认需为0)
    • m.b=1时

  • m.c(默认需为0)
    • m.c=1时

  • m.d(默认需为1) x轴拉长(>1)/缩短(<1)
    • m.d=0.5时

  • m.e(默认需为0) 向x轴移动(>0)/向-x轴移动(<0)
    • m.d=300时

  • m.f(默认需为0) 向x轴移动(>0)/向-x轴移动(<0)
    • m.f=100时

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

// Create a new path with a rect
var p1 = new Path2D();
p1.rect(0,0,100,100);

// Create another path with a rect
var p2 = new Path2D();
p2.rect(0,0,100,100);

// Create transformation matrix that moves vertically 300 points to the right
var m = document.createElementNS("http://www.w3.org/2000/svg", "svg").createSVGMatrix();
m.a = 1; m.b = 0;
m.c = 0; m.d = 1;
m.e = 300; m.f = 0;

// add the second path to the first path
p1.addPath(p2, m);

// Finally, fill the first path onto the canvas
ctx.fill(p1);