We all remember playing with magnets as kids. One popular experiment to show how magnets work uses iron filings suspended on a sheet of paper held above a bar magnet.
This gives a good visualisation of the size and placement of the magnetic fields surrounding the magnet.
The demo will load in the area below. If nothing happens, click here.
Here you can see an initial attempt to render the effects of a magnetic field by introducing “iron filings” – which are actually just image sprites rendered with the Pixi.js library and animated using a mathematical function.
There are still a lot of features that I hope to eventually implement, to create more realistic behaviour (listed below).
For reference, here’s an image of the classic “bar magnet with iron filings” experiment which shows the iron filings aligning along the lines of the magnetic fields:
var B = (Math.pow(10, -7) * Math.sqrt(1 + 3 * Math.pow(Math.cos(angle), 2))) / Math.pow(distance/1000, 3);
Now, I’m certainly no mathematician. In fact, I’d class myself more as an engineer (i.e. definitely not a mathematician) but it seems like the above formula does the trick, and generates something that looks like it probably works as a magnetic field simulation. To the engineer part of my brain, that’s good enough.
From my understanding, the formula above will estimate the magnetic field strength at a given point, but I was trying to simulate a bar magnet (i.e. made up of a large number of individual magnetic points). So, to achieve that, I calculated the field strength at multiple points on the “magnet”, and then from that derived an average. Again, this may not be strictly the right approach, but it seems to work.
There’s plenty more to do here though:
Robin is the dedicated developer behind Solarise.dev. With years of experience in web development, he's committed to delivering high-quality solutions and ensuring websites run smoothly. Always eager to learn and adapt to the ever-changing digital landscape, Robin believes in the power of collaboration and sharing knowledge. Outside of coding, he enjoys diving into tech news and exploring new tools in the industry.
If you'd like to get in touch to discuss a project, or if you'd just like to ask a question, fill in the form below.
Send me a message and I'll get back to you as soon as possible. Ask me about anything - web development, project proposals or just say hi!