更新时间:2023-02-05 18:50:50
这里的代码做得更好.
以下是我更改的您应该考虑的事项的细分:
Here's a breakdown of the things that you should take into consideration that I changed:
beginPath
连续添加到路径而不是停止并创建新路径.这是迄今为止最大的性能杀手.您最终会得到一条包含成千上万条线段的路径,这些线段永远不会被清除.render
内部调用的唯一内容是 stroke
.您不需要再次调用 lineTo/moveTo
,当然也不会连续调用.见注释 1.beginPath
. This is by far the biggest performance killer here. You're ending up with a path with thousands and thousands of line segements that never gets cleared.render
is stroke
. You do not need to call lineTo/moveTo
ever again, and certainly not continuously. See note 1.注意 1: 如果您计划在您的应用程序中有多个路径,那么您可能应该缓存这样的路径,因为它们永远不会改变.我有关于如何做到这一点的教程这里.
Note 1: If you plan to have more than one path in your application then you should probably cache paths like this one since they never change. I have a a tutorial on how to do that here.
当然,如果您做这一切只是为了制作背景,则应将其另存为 png,并且您应该使用 CSS 背景图像.
像这样:http://jsfiddle.net/zHpgV/4/
然后突然你的渲染程序变得相当小:
Then suddenly your render routine is rather small:
function render() {
c.clearRect(0, 0, scale, scale);
c.fillText('{0}, {1}'.format(mouseX, mouseY), 0.5, 1.5);
}