JavaScript 鼠标移动导致延迟?

JavaScript mouse movement causing lag?

我对 JavaScript 中的编码很陌生,很困惑!

当您第一次 运行 此代码时,一切正常。然而,一旦你移动了一点,你就会开始意识到它变得越来越滞后,几乎无法播放。

这是什么原因造成的?

我该如何解决?

<html>
<head>
    <title>Rotate</title>
    <script src="Tank.js"></script>
</head>
<body>
    <canvas id="canvas" style="border:1px solid #ccc" width="700" height="500">
    </canvas>
    <script>
        var canvas = document.getElementById('canvas');
        var context = canvas.getContext('2d');
        var mouseX, mouseY;

        function Tank(x, y){
            this.x = x;
            this.y = y;
            this.angle;
        }

        Tank.prototype.draw = function(){
            context.save();
            context.translate(this.x, this.y);
            context.rotate(this.angle);
            context.fillStyle = "green";
            context.arc(0,0,30,0,2*Math.PI);
            context.fill();
            context.fillStyle = "red";
            context.fillRect(0,-10,50,20);
            context.restore();
        }

        Tank.prototype.update = function(mouseX, mouseY){
            var dx = mouseX - this.x;
            var dy = mouseY - this.y;
            this.angle = Math.atan2(dy, dx);
        }

        canvas.addEventListener('mousemove', mouseMove);

        function mouseMove(evt){
            mouseX = evt.x;
            mouseY = evt.y;     
        }

        var tank = new Tank(350, 250);

        function gameLoop(){
            context.clearRect(0,0, canvas.width, canvas.height);
            tank.draw();
            tank.update(mouseX, mouseY);
        }

        setInterval(gameLoop,20);   
    </script>
</body>
</html>

您需要调用 context.beginPath() before starting new paths. Without this, your calls to arc 构建相同的路径,每一帧都有越来越多的子路径,因此每个连续的帧都在绘制更复杂的形状。随着时间的推移,它也占用越来越多的内存。

已修复 fiddle:https://jsfiddle.net/mmkzes7n/2/

在这个fiddle中我也把setInterval换成了requestAnimationFrame,我觉得这个主意不错。您可以阅读相关内容并决定是否要进行相同的更改。 (然后您可以将其增强为仅在实际需要重绘时才请求动画帧。目前这仅在鼠标位置移动时才会发生,但随着游戏的发展,我相信它会不止于此。)