<canvas id="canvas" width="400" height="400"></canvas>
// 创建画球函数
function Ball() {
this.x = 0;
this.y = 0;
this.radius = 10;
this.fillStyle = "#f85455";
this.draw = function(cxt) {
cxt.fillStyle = this.fillStyle;
cxt.beginPath();
cxt.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, true);
cxt.closePath();
cxt.fill();
}
}
// requestAnimationFrame的兼容性写法
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
// 获得当前鼠标位置
function getMouse(ev) {
var mouse = {
x: 0,
y: 0
};
var event = ev || window.event;
if(event.pageX || event.pageY) {
x = event.x;
y = event.y;
}else {
var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
x = event.clientX + scrollLeft;
y = event.clientY + scrollTop;
}
mouse.x = x;
mouse.y = y;
return mouse;
}
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
ball = new Ball(),
easing = 0.05,
targetX = canvas.width / 2,
targetY = canvas.height / 2,
isMouseDown = false,
mouse = {x: 0, y: 0};
ball.x = 5;
ball.y = 5;
canvas.addEventListener("mousedown", function(ev) {
function isMouseInBall(oBall) {
mouse = getMouse(ev);
// 判断鼠标是否在圆球内
if (Math.pow(mouse.x - ball.x, 2) + Math.pow(mouse.y - ball.y, 2) <= Math.pow(ball.radius, 2)) {
isMouseDown = true;
canvas.addEventListener("mouseup", onMouseUp, false);
canvas.addEventListener("mousemove", onMouseMove, false);
}
}
isMouseInBall(ball);
}, false);
function onMouseUp() {
isMouseDown = false;
drawFrame();
canvas.removeEventListener("mouseup", onMouseUp, false);
canvas.removeEventListener("mousemove", onMouseMove, false);
}
function onMouseMove(ev) {
mouse = getMouse(ev);
ball.x = mouse.x;
ball.y = mouse.y;
ball.draw(context);
}
// 缓动动画函数
var animRequest = null;
function drawFrame() {
animRequest = window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var vx = (targetX - ball.x) * easing;
var vy = (targetY - ball.y) * easing;
ball.x += vx;
ball.y += vy;
ball.draw(context);
}
drawFrame();
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.