Using JavaScript to create Lewis structures

Recently I watched the Crash Course Chemistry video about Lewis structures, and I thought it would be a fun project to try and create a way of displaying these diagrams using the p5.js graphics library.

You can see the finished product here: https://brychanthomas.github.io/lewis/ . It only works on a desktop computer rather than a mobile device. You can add atoms by entering their periodic table symbols with the keyboard. For atoms with two letter symbols, you must hold down shift for the first letter. You can then add covalent bonds between atoms by clicking between them.

The outer shell of each atom is represented by an array of numbers, where electrons involved in a bond are represented by 2, electrons not involved in bonding are represented by 1 and empty spaces are represented by 0. If two atoms both have empty spaces and you click between them, they will form a covalent bond.

If one atom has empty spaces and the other has electrons not involved in bonding, they will form a coordinate covalent bond where the second atom shares two electrons with the first atom. This allows molecules such as carbon monoxide to be represented:

However, the ability to form coordinate bonds creates an issue because many non-existent molecules can form. For example:

Here a carbon and an oxygen atom have formed carbon monoxide, but the carbon has then donated two electrons to form a coordinate bond with another oxygen atom. In reality this does not happen. The problem is that it is very difficult to predict when a coordinate bond forms. According to this forum it is possible, but it needs complex quantum physics.

However, I am happy with how the program has turned out because I am able to accomplish my original goal of representing simple molecules such as ethanoic acid:

To make it easier to add elements, I have used a class to represent elements and a dictionary to connect these classes to keyboard buttons. Each element needs an atomic number, a symbol and a colour:

Elements = { //elements are stored in a dictionary with the key being the keyboard buttons you must press
	"o": new Element(8, "O", color(255, 0, 0)),
	"c": new Element(6, "C", color(0,0,0)),
	"h": new Element(1, "H", color(150 ,150,150)),
	"n": new Element(7, "N", color(0 ,0,255)),
	"f": new Element(9, "F", color(219, 191, 29)),
	"Cl": new Element(17, "Cl", color(32, 161, 27)),
	"Br": new Element(35, "Br", color(219, 116, 20)),
	"s": new Element(16, "S", color(219,212,0)),
	"p": new Element(15, "P", color(150,0,0)),
	"Si": new Element(14, "Si", color(217,2,181))
};

Here are all of the elements that I’ve added to the program:

Metals cannot be used because they form ionic and metallic but not covalent bonds, and other atoms cannot be used because they do not follow the octet rule.

The full program can be found on GitHub here.

Leave a comment

Design a site like this with WordPress.com
Get started