3 ms·
In the Electrical Potential lesson, you have a super cool Scalar Field simulation. I noticed you were doing some tricks to get it to render quickly, like render
by spiralganglion 8y ago
In the Electrical Potential lesson, you have a super cool Scalar Field simulation. I noticed you were doing some tricks to get it to render quickly, like rendering at a lower resolution while animating. I do a lot of HTML canvas work, so I figured I'd take a crack at implementing something like it, to see if I could improve the render performance.
Here's what I came up with: http://electrons.surge.sh http://electrons.surge.sh
• (Small Improvement) When updating the particle positions (your physicsAll function), you can skip a bunch of loop iterations and redundant distance math by using j > i rather than i != j, and updating both particles together: https://github.com/ivanreese/electrons/blob/8b21d1cf8c80e16c1d47b3a00a43e30ed6267513/source/script/particles.coffee#L40-L51 https://github.com/ivanreese/electrons/blob/8b21d1cf8c80e16c...
• (Big Improvement) Rather than using fillRect to draw each square of the scalarField, manipulate the canvas pixel data directly. Use context.getImageData() to get a ByteArray, then loop through it and update the color in each pixel. Much faster than using fills when you want to color every pixel in the canvas independently: https://github.com/ivanreese/electrons/blob/8b21d1cf8c80e16c1d47b3a00a43e30ed6267513/source/script/particles.coffee#L68-L96 https://github.com/ivanreese/electrons/blob/8b21d1cf8c80e16c...
• (Aesthetic Improvement) I also render at a lower resolution, and I use the CSS blur filter to smooth out the result: canvas { filter: blur(4px) }
I hope some of these suggestions are helpful. None of them require switching to a new rendering technology (like WebGL), and it should be pretty easy to slot them in to your existing code. Feel free to drop me a line if you'd like help implementing anything.
Last but not least, thanks for creating this fantastic educational resource! I work for a learning media company that produces some electrical content, and I shared your work with my teammates as an example of what we could aspire to. It was a real hit.
- lilgreenland 8y agothanks! This is great! I'm going to work on implementing these changes. The context.getImageData() might enable me to improve some other simulations as well.
- mercer 8y agoI just want to say comments like these make me very happy. It really captures a kind of 'hacker spirit' that I try to be part of (and not just when it comes to programming). Thanks!