效果如图所示,可以实现精准拖拉和触界反弹
var canvas = document.getElementById("canvas");
var cxt = canvas.getContext("2d");
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var balles = [];
function Ball(x, y, radius, speed) {
this.x = x;
this.y = y;
this.radius = radius;
this.speed = speed;
}
var speed = {
x: 0,
y: 0
};
balles.push(new Ball(centerX, centerY, 30, speed));
var isPressed = false;
var ball = balles[0];
var DownX = 0;
var DownY = 0;
var CsX = 0,
CsY = 0;
function drawBall() {
cxt.clearRect(0, 0, canvas.width, canvas.height)
cxt.beginPath();
cxt.fillStyle = "red";
if(!isPressed) {
ball.x += ball.speed.x;
ball.y += ball.speed.y;
}
if(ball.x > canvas.width - ball.radius || ball.x < 0 + ball.radius) {
// ball.x=centerX;
// ball.y=centerY;
// ball.speed={x:0,y:0}
ball.speed.x = -ball.speed.x;
}
if(ball.y > canvas.height - ball.radius || ball.y < 0 + ball.radius) {
ball.speed.y = -ball.speed.y;
}
cxt.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2, true);
cxt.fill();
cxt.closePath();
requestAnimationFrame(drawBall);
}
function isMoveUpBall(ball, x, y) {
var vx = x - ball.x;
var vy = y - ball.y;
var dist = Math.sqrt(vx * vx + vy * vy);
if(dist < ball.radius) {
return true;
} else {
return false;
}
}
function draw(event) {
var x = event.point.x + CsX;
var y = event.point.y + CsY;
console.log(event.point.x, x)
if(isPressed && isMoveUpBall(ball, event.point.x, event.point.y)) {
ball.x = x;
ball.y = y;
ball.speed.x = x - DownX;
ball.speed.y = y - DownY;
DownX = x;
DownY = y;
}
}
function move(event) {
draw(event);
}
function down(event) {
isPressed = true;
DownX = event.point.x;
DownY = event.point.y;
draw(event);
}
function up(event) {
isPressed = false;
draw(event);
}
window.onload = function() {
drawBall();
tool.MT(canvas, move, down, up);
}