Review of JavaScript Syntax (Basics)

I’ve been taking the Coursera course Programming and the Web for Beginners by Duke University. It’s the 1st course for the Java Programming: An Introduction to Software specialization.

Here I am going to review and summarize the JavaScript syntax I learned from this course.

I am using Duke’s JavaScript environment to practice coding. This webpage also includes examples.

1. create & display image

var image = new SimpleImage("duke_blue_devil.png");
print(image);

2. set pixel colors

  • set image to black
for (var pixel of image.values()) {
   pixel.setRed(0);
   pixel.setGreen(0);
   pixel.setBlue(0);
}

// Note: “pixel” is often replaced by “p”, and “image” can be replaced by other image names, as long as the variable names are consistent across lines.

// Method call statement such as pixel.setRed() consists of a variable, a dot and a name of the method being called.

// RGB values can be set from 0 to 255.

  • convert image to grey scale
for (var p of flower.values()) {
    var avg = (p.getGreen() + p.getRed() + p.getBlue()) / 3;
    p.setRed(avg);
    p.setBlue(avg);
    p.setGreen(avg);
}
  • weighted gray scale
for (var p of image.values()) {
    var avg = 0.3 * p.getRed() + 0.59 * p.getGreen() + 0.11 * p.getBlue();
    p.setRed(avg);
    p.setBlue(avg);
    p.setGreen(avg);
    debug(avg);
}

//If we put debug() in the for loop, it will print out all the values.

3. get pixel colors

p.getRed()

4. (x,y) coordinates, width, height

var image = new SimpleImage (300,200);

// create white image with a size

p.getX()
p.getY()

// get pixel (x,y) coodinates

w=image.getWidth();
h=image.getHeight();

// get image width/height, and assign the value to a variable

5. operators

==    !=    &&    ||

6. if, else if, else

var image = new SimpleImage("hilton.jpg");
 print(image);
 w = image.getWidth();
for (var p of image.values()) {
 x = p.getX();
 if (x < w/3) {
 p.setRed (255);
 }
 else if (x > (2/3)*w) {
 p.setBlue (255);
 }
 else {
 p.setGreen (255);
 }
 }
print(image);

7. combine images using a green screen

Image b

image.getPixel(x, y);
image.setPixel(x, y, p);

 

Advertisements

2 thoughts

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s