我想使我的矩形的「動畫」更加流暢。目前它真的很笨重。我知道它的原因。其中一個座標變成另一個之前的要求值。例如,如果我目前在(0,0)並且我需要去(150,75),並且我每次都等於每秒增加一個,那麼y線比x線快得多。使移動矩形更加平滑
var canvas = document.getElementById('canvas');
var ctx = document.getElementById('canvas').getContext('2d');
var aniTimer;
var x;
var y;
var tx = tx || 0;
var ty = ty || 0;
var xDir;
var yDir;
function followMouse(e) {
x = e.offsetX;
y = e.offsetY;
cancelAnimationFrame(aniTimer);
moveObject();
}
function moveObject() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (x < tx) {
xDir = -1;
} else {
xDir = 1;
}
if (y < ty) {
yDir = -1;
} else {
yDir = 1;
}
tx = tx != x ? tx + xDir : tx;
ty = ty != y ? ty + yDir : ty;
ctx.fillRect(tx - 25 , ty + 25, 50, 10);
if (tx != x || ty != y) {
aniTimer = window.requestAnimationFrame(moveObject);
}
}
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
canvas.addEventListener('mousemove', _.throttle(function(e) {
followMouse(e);
}, 100));
window.addEventListener('resize', resizeCanvas, false);
resizeCanvas();
html,
body {
margin: 0;
height: 100%;
}
canvas {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<canvas id="canvas"></canvas>
你想達到什麼樣的動畫?到目前爲止還不是很清楚 –
我會用圖片添加圖片,給我一分鐘。 – Paran0a