1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| function Ball(x, y, radius, dx, dy) { this.x = x this.y = y this.dx = dx this.dy = dy this.radius = radius this.draw = function() { ctx.beginPath() ctx.arc(this.x,this.y,this.radius, 0, 2*Math.PI, false) ctx.strokeStyle = 'blue' ctx.stroke() ctx.fill() } this.update = function() { if(this.x + this.radius > canvas.width || this.x-this.radius < 0) { this.dx = -this.dx } if(this.y+this.radius > canvas.height || this.y-this.radius < 0) { this.dy = -this.dy } this.x += this.dx this.y += this.dy this.draw() } }
var ball = new Ball(200,200,3,3,30) function animate() { requestAnimationFrame(animate) ctx.clearRect(0,0,canvas.width,canvas.height) ball.update() }
animate()
|