gpt4 book ai didi

javascript - 在 HTML5 Canvas 上同时追踪两条​​路径

转载 作者:行者123 更新时间:2023-12-05 04:13:54 25 4
gpt4 key购买 nike

我的代码在精神上等同于这个片段:

function drawComplicatedThing(ctx) {
let [px, py] = [0, 0];
for (let i = 0; i < 10000; i++) {
let {x, y} = computeExpensive(i);

// black along
ctx.beginPath();
ctx.moveTo(px, py);
ctx.lineTo(x, y);
ctx.strokeStyle = 'black';
ctx.stroke();

// red transpose
ctx.beginPath();
ctx.moveTo(py, px);
ctx.lineTo(y, x);
ctx.strokeStyle = 'red';
ctx.stroke();

[px, py] = [x, y];
}
}

我正在尝试通过批处理对 stroke 的调用来优化代码。例如,我可以这样做:

function drawComplicatedThing(ctx) {
// black along
ctx.moveTo(0, 0);
for (let i = 0; i < 10000; i++) {
let {x, y} = computeExpensive(i);
ctx.lineTo(x, y);
}
ctx.strokeStyle = 'black';
ctx.stroke();

// red transpose
ctx.moveTo(0, 0);
for (let i = 0; i < 10000; i++) {
let {x, y} = computeExpensive(i);
ctx.lineTo(y, x);
}
ctx.strokeStyle = 'red';
ctx.stroke();
}

但请注意,现在我调用 computeExpensive 的次数是原来的两倍。这速度较慢,但​​真正的代价是在实践中 computeExpensive 实际上是一个内联代码块,因此我们的优化强制执行了粗略的代码重复。

重组示例代码以避免代码重复很容易(只需将点缓存到数组中),但通常可能存在条件绘图逻辑,并且在重复时重组起来要困难得多。

如果我可以同时追踪两条​​路径,就很容易解决这个问题。像这样:

function drawComplicatedThing(ctx) {
let ctx2 = ctx.independentCopy(); // <-- NOT REAL, but you get the idea
ctx.moveTo(0, 0);
ctx2.moveTo(0, 0);
for (let i = 0; i < 10000; i++) {
let {x, y} = computeExpensive(i);
ctx.lineTo(x, y);
ctx2.lineTo(y, x);
}
ctx.strokeStyle = 'black';
ctx.stroke();
ctx2.strokeStyle = 'red';
ctx2.stroke();
}

HTML5 中是否存在这种功能,或者我是否需要围绕一次只能跟踪一个笔画路径来构建我的代码?

最佳答案

您可以创建独立于 Canvas 上下文进行绘制的路径。

const pathBlack = new Path2D()
const pathRed = new Path2D()
pathBlack.moveTo(0, 0);
pathRed.moveTo(0, 0);

for (let i = 0; i < 10000; i++) {
let {x, y} = computeExpensive(i);
pathBlack.lineTo(x, y);
pathRed.lineTo(y, x);
}

ctx.strokeStyle = 'black';
ctx.stroke(pathBlack);
ctx.strokeStyle = 'red';
ctx.stroke(pathRed);

关于javascript - 在 HTML5 Canvas 上同时追踪两条​​路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36146461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com