Here's the code made much better.
http://jsfiddle.net/zHpgV/3/
Here's a breakdown of the things that you should take into consideration that I changed:
- Continuous adding to a path instead of stopping and creating a new path with
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.
- Continuously making the same path over and over when it only needs to be made once, on initialization. That is, the only thing you need to call inside of
render
is stroke
. You do not need to call lineTo/moveTo
ever again, and certainly not continuously. See note 1.
- Stroking twice for one path
- Stroking inside a for loop
- Redrawing a background instead of setting CSS background
- Setting the line cap over and over
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.
Of course, if you are doing all of this to just make a background, it should be saved as a png and you should be using a CSS background-image.
Like so: 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);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…