我想做的是单击 Canvas 上的一个位置,然后让一个点沿着路径直接到达我选择的位置。
这是我到目前为止的代码。
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var rect = canvas.getBoundingClientRect()
//
var clickedChords = {
x: 0,
y: 0
};
var player = {
x: 100,
y: 100
};
canvas.addEventListener("mousedown", getChords, false);
function getChords(e) {
clickedChords.x = e.pageX - rect.left;
clickedChords.y = e.pageY - rect.top;
}
function draw() {
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle= 'black';
ctx.beginPath();
ctx.arc(clickedChords.x,clickedChords.y,3,0,360);
ctx.arc(player.x,player.y,3,0,360);
ctx.fill();
if(player.x > clickedChords.x && player.x !== clickedChords.x){
player.x -= 1;
}
if(player.x < clickedChords.x && player.x !== clickedChords.x){
player.x += 1;
}
if(player.y < clickedChords.y && player.y !== clickedChords.y){
player.y += 1;
}
if(player.y > clickedChords.y && player.y !== clickedChords.y){
player.y -= 1;
}
}setInterval(draw, 10);
现在我所能做的就是让点跟随 45 度 Angular ,然后点击并跟随我点击位置的 x 或 y 值。我尝试使用斜率公式,但我对如何将其实现到我的代码中一无所知。
感谢您的帮助,因为我真的陷入困境。
最佳答案
您可以为此使用插值:
var t = 0, // will be in range [0.0, 1.0]
oldPlayerX, // need these for interpolation
oldPlayerY;
function getChords(e) {
clickedChords.x = e.pageX - rect.left;
clickedChords.y = e.pageY - rect.top;
oldPlayerX = player.x, // copy these as we need them as-is
oldPlayerY = player.y;
draw();
}
function draw() {
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle= 'black';
ctx.beginPath();
ctx.arc(clickedChords.x,clickedChords.y,3,0,360);
ctx.arc(player.x,player.y,3,0,360);
ctx.fill();
if (t <= 1) {
player.x = oldPlayerX + (clickedChords.x - oldPlayerX) * t;
player.y = oldPlayerY + (clickedChords.y - oldPlayerY) * t;
t += 0.05; // determines speed
requestAnimationFrame(draw); // use this instead of setInterval
}
}
插值本身发生在这些行上:
player.x = oldPlayerX + (clickedChords.x - oldPlayerX) * t;
player.y = oldPlayerY + (clickedChords.y - oldPlayerY) * t;
它基本上区分了新旧位置。 t
将确定将多少差异添加到原始位置,即。如果 t=0 则什么也没有,如果 t=1 则将全部差值添加到旧位置,这显然等于新位置。介于两者之间的任何内容(对于 t
)都会添加一个百分比,允许您为该点设置动画。
requestAnimationFrame
允许您同步动画以监视刷新。 10 毫秒的 setInterval 值对于浏览器的处理来说太短了(屏幕刷新 @ 60 Hz 的最小值为 16.7 毫秒)。
希望这有帮助!
关于javascript - 让点跟随选定的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23256778/