【发布时间】:2020-08-07 11:18:49
【问题描述】:
我和一个朋友正在玩分形,并想创建一个交互式网站,您可以在其中更改生成分形的值,并且您可以看到它对生活的影响。在小分辨率测试中,网站响应速度很快,但仍然很慢。
drawFractal = () => {
for (let x = 0; x < this.canvas.width; x++) {
for (let y = 0; y < this.canvas.height; y++) {
const belongsToSet = this.checkIfBelongsToMandelbrotSet(x / this.state.magnificationFactor - this.state.panX, y / this.state.magnificationFactor - this.state.panY);
if (belongsToSet === 0) {
this.ctx.clearRect(x,y, 1,1);
} else {
this.ctx.fillStyle = `hsl(80, 100%, ${belongsToSet}%)`;
// Draw a colorful pixel
this.ctx.fillRect(x,y, 1,1);
}
}
}
}
checkIfBelongsToMandelbrotSet = (x,y) => {
let realComponentOfResult = x;
let imaginaryComponentOfResult = y;
// Set max number of iterations
for (let i = 0; i < this.state.maxIterations; i++) {
const tempRealComponent = realComponentOfResult * realComponentOfResult - imaginaryComponentOfResult * imaginaryComponentOfResult + x;
const tempImaginaryComponent = this.state.imaginaryConstant * realComponentOfResult * imaginaryComponentOfResult + y;
realComponentOfResult = tempRealComponent;
imaginaryComponentOfResult = tempImaginaryComponent;
// Return a number as a percentage
if (realComponentOfResult * imaginaryComponentOfResult > 5) {
return (i / this.state.maxIterations * 100);
}
}
// Return zero if in set
return 0;
}
这是处理分形生成的算法。然而,我们遍历画布的每个像素,这是非常低效的。结果整个网站真的很慢。我想问一下使用 html canvas 是个好主意还是有更有效的替代方案?或者我可以优化 drawFractal() 函数以提高效率吗?我不知道如何从这一点继续,因为我没有经验,希望得到任何反馈!
【问题讨论】:
-
您好@Middle,令人印象深刻的项目,但您的问题似乎更像是您项目的广告和推荐页面,而不是问题。请查看how to ask a good question 页面并重新编辑您的问题。如果您没有实际问题,请删除此帖子。
-
@MrPizzaGuy 谢谢,我现在改了。它更像是一个个人项目,因为它永远不会是一个网站。谢谢你
标签: javascript html reactjs html5-canvas fractals