javascript - JavaScript画布将元素移动到目标坐标
问题描述
我正在尝试将元素(具有自己的起始坐标)移动到画布上的自定义位置。我怎样才能让它直接移动到新的位置(沿着一条直线)?
<html>
<head></head>
<body>
<canvas id="canvas" width="600px" height="600px"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var mouseX, mouseY;
document.addEventListener("click", function (e) {
mouseX = e.clientX;
mouseY = e.clientY;
console.log(mouseX, mouseY)
})
function background() {
ctx.fillStyle = "#505050";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
var ball = {
x: 100,
y: 100,
draw: function () {
ctx.fillStyle = "#F00000";
ctx.beginPath();
ctx.arc(this.x, this.y, 30, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
}
}
setInterval(function () {
background();
ball.draw()
//example
if (mouseX > ball.x)
ball.x++;
if (mouseY > ball.y)
ball.y++;
}, 1000 / 60)
</script>
</body>
</html>
//example 下的内容仅适用于纯左/右/上/下/对角线运动,但不适用于除这些之外的自定义位置。我希望它始终沿着直线直接移动到自定义位置。
解决方案
您应该使用dx
并dy
确定在每个渲染上移动每个方向的距离。我还建议使用window.requestAnimationFrame
来调用draw
每一帧。您还可以设置stepWidthFactor
相对距离。
<canvas id="canvas" width="600px" height="600px"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var stepWidthFactor = 200;
var mouseX, mouseY;
function background() {
ctx.fillStyle = "#505050";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
var ball = {
x: 100,
y: 100,
dx: 0,
dy: 0,
draw: function () {
ctx.fillStyle = "#F00000";
ctx.beginPath();
ctx.arc(this.x, this.y, 30, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
}
}
function draw() {
background();
ball.draw();
var shouldMove = Math.abs(ball.x - mouseX) > 1 || Math.abs(ball.y - mouseY) > 1;
if(shouldMove) {
ball.x += ball.dx;
ball.y += ball.dy;
} else {
ball.dx = 0;
ball.dy = 0;
}
window.requestAnimationFrame(draw)
}
document.addEventListener("click", function (e) {
mouseX = e.clientX;
mouseY = e.clientY;
ball.dx = (ball.x - mouseX) / stepWidthFactor * -1;
ball.dy = (ball.y - mouseY) / stepWidthFactor * -1;
})
draw();
</script>
推荐阅读
- sql - SQL 查询。获取按 desc 排序的相似行
- excel - 多个空 Excel VBA 项目
- r - 检查观察是否落在 R 中的多个区间中
- node.js - 如何在 node.js 中存储会话值?
- python - 打印语句后出现缩进错误
- javascript - 如何在没有任何库的情况下从 JavaScript 使用 SVG 动画线
- pandas - 用数字和字符串重新采样时间序列的集合
- php - 在 Laravel 7 中使用 AJAX 调用没有数据或表单的 PHP 函数
- angular - 从 Angular 调用 local.net core Web API
- google-apps-script - 与互联网上的任何人共享数据洞察报告,但让他们输入凭据以查看它