首页 > 解决方案 > 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 下的内容仅适用于纯左/右/上/下/对角线运动,但不适用于除这些之外的自定义位置。我希望它始终沿着直线直接移动到自定义位置。

标签: javascriptanimationcanvas2d

解决方案


您应该使用dxdy确定在每个渲染上移动每个方向的距离。我还建议使用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>


推荐阅读