仅变换Path2D的路径

问题描述 投票:0回答:1

在canvas 2D API中,我们可以首先使用一个上下文的转换定义一个子路径,然后仅对fill()stroke()调用更改该上下文的转换,这将对stylings产生影响,例如[ C0],fillStyle和其他可见属性,但将保留定义的子路径。当我们要放大矢量形状同时保持相同的笔触宽度时,这非常方便。

这是一个简单的示例,其中只有lineWidth受变量zoom转换的影响:

lineWidth
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

let zoom = 1;
let speed = 0.1;
requestAnimationFrame(update);

function update() {
  if( zoom >= 10 || zoom <= 0.1 ) speed *= -1;
  zoom += speed;
  draw();
  requestAnimationFrame(update);
}

function draw() {
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.clearRect(0,0,canvas.width,canvas.height);
  // define the subpath at identity matrix
  ctx.beginPath();
  ctx.moveTo(10 ,80);
  ctx.quadraticCurveTo(52.5,10,95,80);
  ctx.quadraticCurveTo(137.5,150,180,80);
  // stroke zoomed
  ctx.setTransform(zoom, 0, 0, zoom, 0, 0);
  ctx.stroke();
}

使用<canvas id="canvas"></canvas> API,我们必须直接以Path2Dctx.fill(path)方法传递此子路径。这意味着我们无法像以前一样将样式与子路径声明分开:

ctx.stroke(path)
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

let zoom = 1;
let speed = 0.1;
requestAnimationFrame(update);

function update() {
  if( zoom >= 10 || zoom <= 0.1 ) speed *= -1;
  zoom += speed;
  draw();
  requestAnimationFrame(update);
}

function draw() {
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.clearRect(0,0,canvas.width,canvas.height);
  // define the subpath at identity matrix
  // (declared in 'draw' just for the example, would be the same anyway outside)
  const path = new Path2D("M 10 80 Q 52.5 10, 95 80 T 180 80");
  // stroke zoomed
  ctx.setTransform(zoom, 0, 0, zoom, 0, 0);
  ctx.stroke(path);
}

使用此方便的Path2D API时,没有办法这样做吗?

javascript html5-canvas transformation
1个回答
0
投票
[一种通过将<canvas id="canvas"></canvas>传递给DOMMatrix1方法来变换Path2D对象的方法。
© www.soinside.com 2019 - 2024. All rights reserved.