Not logged in. Login

Exercise 10

For this exercise, start with the the provided HTML page. You will create the JavaScript code to make it work as follows

Clickable Blocks

In the first container (id="svg1"), create a 200×200 SVG Paper object.

When the user types a number in the text input and clicks the Add More button, we will add that number of squares to the SVG. That will require getting the value from the input, and using it as the limit of a for loop.

To make things a little more interesting, we will add the blocks in random positions. The built-in Math.random() function will give us a random number between 0 and 1 every time we call it. Here is some code to add one rectangle:

x = Math.random() * 180
y = Math.random() * 180
r = paper.rect(x, y, 20, 20)
filled = {
  'fill': '#ddf'
}
r.attr(filled)

Shapes created by Raphaël have many of the same events as jQuery elements. In particular, you can do something when a shape is clicked by calling r.click(disappear) (assuming you have a function disappear defined).

In the handler function, the special variable this holds the shape that was clicked on. The Raphaël .remove() function can make it disappear. Use this function as the squares' click handler:

disappear = function() {
  this.remove()
}

(The code above creates the squares with a fill: if they don't have a fill colour, then only the outlines are clickable, which is vary hard to trigger.)

Spin Them

When the squares appear (in the previous part), we want them to look a little more interesting. When they appear, start an animation to have them spin in a random way.

Use Math.random() to create a random value from -720 to 720, which represents spinning up to two full rotations in either direction. (Hint: multiply by 1440 and subtract 720.)

Once you have the angle, you can build a transform string from it: the result should be like 'r123', depending on the angle you generate. Animate that transform on the square.

Video: Exercise 10 behaviour

Expanding Circles

In the second container (id="svg2"), create another 200×200 SVG Paper object.

Each time the Add Another button is clicked, a circle should be drawn on the image. The first should have radius 10, then 20, 30, 40,.

Submitting

Upload the files to the course web server, as you have before and make sure everything is working. You may want to create a folder exercise10. Submit the URL of your HTML page to the CourSys activity Exercise 10.

Updated Wed Aug. 24 2016, 12:06 by ggbaker.