小球可以跟着鼠标移到,点击小球时会按既定的坐标移到小球(不再跟着鼠标移到),鼠标移出canvas,此时动画停止,鼠标进入动画时动画开始

<canvas id="canvas" width="600" height="300" style="border:1px solid #ccc;"></canvas>


<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var raf;
var running = false;
var ball = {
    x: 100,
    y: 100,
    vx: 5,
    vy: 2,
    radius: 25,
    color: "purple",
    draw: function() {
        context.beginPath();
        context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, true);
        context.closePath();
        context.fillStyle = this.color;
        context.fill();
    }
}

function clear() {
    context.fillStyle = 'rgba(255,255,255,0.3)';
    context.fillRect(0, 0, canvas.width, canvas.height);
}

function draw() {
    clear()
    ball.draw();
    ball.x += ball.vx;
    ball.y += ball.vy;
    //加速度,
    ball.vy *= .99;
    ball.vy += .25;
    //边界检测,
    if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) {
        ball.vy = -ball.vy
    }
    if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) {
        ball.vx = -ball.vx
    }
    //递归执行draw()
    raf = window.requestAnimationFrame(draw)
}

canvas.addEventListener("mousemove", function(e) {
    if (!running) {
        clear()
		ball.x = e.layerX;
		ball.y = e.layerY;
        //ball.x = e.clientX;
        //ball.y = e.clientY;
        ball.draw()
    }
})

canvas.addEventListener("click", function(e) {
    if (!running) {
        raf = window.requestAnimationFrame(draw);
        //作用是避免准备移出时,圆圈跟着鼠标运动
        running = true;
    }
})
canvas.addEventListener("mouseout", function() {
    window.cancelAnimationFrame(raf);
    //重置running,为下一次mousemove做准备
    running = false;
})
ball.draw()
</script>


查看动画效果

02-26 15:32