MDN breakout step 3

This commit is contained in:
Dan Buch 2016-12-31 23:29:00 -05:00
parent af3e1f0b24
commit f97e05aa11
No known key found for this signature in database
GPG Key ID: FAEF12936DD3E3EC

View File

@ -11,29 +11,55 @@ canvas { background: #eee; display: block; margin: 0 auto; }
<body> <body>
<canvas id="myCanvas" width="480" height="320"></canvas> <canvas id="myCanvas" width="480" height="320"></canvas>
<script> <script>
var canvas = document.getElementById("myCanvas"); (function() {
var ctx = canvas.getContext("2d"); var canvas = document.getElementById("myCanvas");
var x = canvas.width/2; var ctx = canvas.getContext("2d");
var y = canvas.height-30; var ballRadius = 10;
var dx = 2; var ballColor = '#0095DD';
var dy = -2; var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
function drawBall() { function randInt(min, max) {
ctx.beginPath(); min = Math.ceil(min);
ctx.arc(x, y, 10, 0, Math.PI*2); max = Math.floor(max);
ctx.fillStyle = "#0095DD"; return Math.floor(Math.random() * (max - min)) + min;
ctx.fill(); }
ctx.closePath();
}
function draw() { function randColor() {
ctx.clearRect(0, 0, canvas.width, canvas.height); return 'rgba(' + ([
drawBall(); randInt(0, 255),
x += dx; randInt(0, 255),
y += dy; randInt(0, 255)
} ].map(function(elem, i) { return '' + elem; }).join(',')) + ', 1.0)'
}
setInterval(draw, 10); function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = ballColor;
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
x += dx;
y += dy;
if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
dy = -dy;
ballColor = randColor();
}
if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
dx = -dx;
ballColor = randColor();
}
}
setInterval(draw, 10);
})();
</script> </script>
</body> </body>
</html> </html>