Curve Bounce
HTML
<!-- We'll be drawing here -->
<canvas id="canvas" width="600" height="400">Your browser does not appear to support HTML5. Try upgrading your browser to the latest version. <a href="http://www.whatbrowser.org">What is a browser?</a>
<br />
<br /><a href="http://www.microsoft.com/windows/internet-explorer/default.aspx">Microsoft Internet Explorer</a>
<br /> <a href="http://www.mozilla.com/firefox/">Mozilla Firefox</a>
<br /> <a href="http://www.google.com/chrome/">Google Chrome</a>
<br /> <a href="http://www.apple.com/safari/download/">Apple Safari</a>
</canvas>
CSS
#canvas {
background-color:#000;
display:block;
margin:20px auto;
}
JavaScript
// initialize stage and ball globally
var stage, ball;
// set ball's initial velocity
var vx = 10,
vy = 10;
/*
* runs when index.html is fully loaded
*/
window.onload = function () {
//initialize stage object, where "canvas" references the id of our canvas
stage = new createjs.Stage("canvas");
// initialize ball object
ball = new createjs.Shape();
// select ball color to be red.
ball.graphics.beginFill("#ff3333");
// draw circle of radius 5 at position (0, 0) relative to the ball's
// coordinates
ball.graphics.drawCircle(0, 0, 5);
// set ball object's coordinates
ball.x = 120;
ball.y = 50;
// add our ball to stage so that it actually gets drawn.
// (this needs to be done only once per object)
stage.addChild(ball);
// initialize curve object
curve = new createjs.Shape();
// set line width to 2px
curve.graphics.setStrokeStyle(2);
// select a random color for the line
curve.graphics.beginStroke(createjs.Graphics.getRGB(Math.random() * 255 | 0, Math.random() * 255 | 0, Math.random() * 255 | 0));
// start first line segment at position (0, f(0))
curve.graphics.moveTo(0, f(0));
// keep on drawing line segments to (i, f(i)) as i moves across the width of the canvas
for (var i = 0; i < stage.canvas.width; i++) {
curve.graphics.lineTo(i, f(i));
}
// add our curve object to stage so that it actually gets drawn.
stage.addChild(curve);
// draw all shapes to canvas
stage.update();
// set framerate to 60FPS
createjs.Ticker.setFPS(60);
// call tick(event) on every "tick"
createjs.Ticker.addEventListener("tick", tick);
};
/*
* called every frame (60 times per second)
*/
function tick() {
// check if a crossing is about to happen.
if ((ball.y + vy) >= f(ball.x + vx)) {
// if ball would cross the curve on next frame, log the message "crossed" to console
//console.log("crossed");
var J =...