html
<canvas id="canvas"></canvas>
js
<script>
var canvas = document.getElementById('canvas')
canvas.width = 400
canvas.height = 400
var ctx = canvas.getContext('2d')
var x = 100
setInterval(function() {
x++;
ctx.clearRect(0,0, canvas.width, canvas.height);
ctx.beginPath()
ctx.arc(x, 200,50,0,Math.PI*2, true)
ctx.fillStyle= "navy";
ctx.fill();
ctx.closePath()
},20)
</script>
用面向对象的方法,来移动小球
<script src="./underscore-min.js"></script>
<script>
var canvas = document.getElementById('canvas')
canvas.width = 400
canvas.height = 400
var ctx = canvas.getContext('2d')
var x = 100
function Ball(x,y, r,color,speed) {
this.x = x;
this.y = y;
this.r = r;
this.color = color;
this.speed = speed;
this.dX = Math.random() *10 -5;
this.dY = Math.random() *10 -5;
this.dR = Math.random() *2+1
ballArray.push(this)
}
Ball.prototype = {
updated: function () {
this.x += this.dX;
this.y += this.dY;
this.r -= this.dR;
if(this.r <= 0) {
this.r = 0.1;
ballArray = _.without(ballArray, this)
}
},
render: function () {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, true)
ctx.fillStyle = this.color;
ctx.fill()
}
}
var ballArray = new Array()
setInterval(function() {
ctx.clearRect(0,0, canvas.width,canvas.height)
for(var i=0; i<ballArray.length; i++) {
ballArray[i].updated();
if(ballArray[i]) {
ballArray[i].render();
}
}
},20);
canvas.addEventListener("mousemove", function(event){
new Ball(event.offsetX, event.offsetY, 50, "red")
})
</script>