Skip to content

Instantly share code, notes, and snippets.

@aresnick
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aresnick/4fedcc22f4b5f84fe2f1 to your computer and use it in GitHub Desktop.
Save aresnick/4fedcc22f4b5f84fe2f1 to your computer and use it in GitHub Desktop.

A simple example of 'objects' in JavaScript

In this example we put together a very small recipe for making circles programmatically as a way of illustrating the basics of creating a class (a recipe for making objects) in JavaScript.


Further Doing

Modify the code so that:

  1. …when the circles are places randomly, they are never placed such that the circle extends over the edge of the window
  2. …when you click on a circle, it migrates to a new location
  3. …instead of circles, n-pointed stars are rendered using multiple, rotated divs overlapping one another

Further Reading

<html>
<body>
<script>
var Circle = function(radius) { // define a new function to make a circle of a given radius
this.radius = radius; // store the radius we're given
this.div = document.createElement('div'); // create the div that we're going to use to display the circle
this.div.style.width = 2 * radius + 'px'; // set its width
this.div.style.height = 2 * radius + 'px'; // and height to twice our radius
this.div.style.borderRadius = radius + 'px'; // set its border-radius to our radius
this.div.style.position = 'absolute'; // position it absolutely
this.div.style.left = Math.floor(Math.random() * 100) + "%"; // so that we can choose a random % left
this.div.style.top = Math.floor(Math.random() * 100) + "%"; // and top to place it
// choose a random number 0 -> 255 for red, green, and blue values
var red = Math.floor(Math.random() * 255)
var green = Math.floor(Math.random() * 255)
var blue = Math.floor(Math.random() * 255)
this.div.style.backgroundColor = 'rgb(' + [red, green, blue].join(',') + ')'; // and set the background color to that random RGB triplet
document.body.appendChild(this.div); // and then stick the div we've created in our page;
};
var myCircles = []; // make an empty array to hold all my Circles
for (var i = 0; i < 10; i++) { // make ten of them
myCircles.push(new Circle(Math.random() * 100)); // with random radii from 0 -> 100, sticking them into the myCircles array
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment