Simple Graphics

Graphics are a good way to learn the structure of the coding language and how the to get things the way you want them to look. We will explore simple shapes and how to position them on the screen. Javascript or JS is a type of computer language that can be used to make graphics and animations. I will be using a type of Processing Javascript that is used on Khan Academy. 

JS uses the same type of command for most shapes. It can be modeled by shape(x-coordinate, y-coordinate, width, height);. The semicolon on the end is really important! If you forget to put it at the end of your command the computer won’t read it and may not run any of your code. Think of you the semicolon as being your go button for each line of code. Meaning the computer will read your command and know all the data, but without that semicolon, it doesn’t know what to do with the information. Your x-coordinate controls how far over your line is going to be and the y-coordinate controls how far down it will be. Pixels are the unit of measure that your computer uses.

Lines

Lines are the exception to the model. They use line(x1,y1,x2,y2). This will tell the computer where to start and stop the line. If you want you a line to run horizontally through the middle of the screen you would put:  line(0,200,400,200);. This tells the computer to put the front of your line at the far left side of the screen and half way down and the end of the line at the far right side of the screen and half way down.

Circles

In this type of JS, a circle is called an ellipse. (Some types of JS call it a circle, but we are going to use an ellipse for simplicity.) The coordinates are based on the middle of your circle. So if you want your circle to be in the exact middle of your 400 by 400 screen and be 10 pixels wide and 100 pixels tall, your code would look like this: ellipse(200,200,10,100);.

Rectangles

A rectangle is a little different. These use the same type of command set up but your coordinates are based on the top left corner of your rectangle. If you wanted a rectangle in the top left corner and you wanted it to be 150 pixels wide and 100 pixels tall, your command would look like this: rect(0, 0, 150,100);. Now if you wanted that same rectangle in the lower right corner you would have to do a little math. In order to find your x-coordinate take the width (150) and subtract it from the width of the canvas (400). To find the y-coordinate take the height (100) and subtract it from the height of the canvas (400). This will give you the command of rect(250,300,150,100);. This will have edges of the rectangle will blend in with the sides of the canvas.

To make it easier to read and edit later, I alway put each command on its own line. The shapes will also appear in the order you have them in your code. Have fun playing around and making all kinds of cool creations!

Leave a Reply

Your email address will not be published. Required fields are marked *