JS Canvas:如何使矩形在到达边界时来回移动

时间:2017-11-08 12:51:57

标签: javascript html canvas

所以我将这个矩形向右移动。如何在矩形到达边界时让矩形反转它。我试图让它来回走动。

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var x = 0;
    var y = 50;
    var width = 10;
    var height = 10;
    function animate() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillRect(x, y, width, height);
        x++;
        if(x <= 490) {
            setTimeout(animate, 33);
        }
    }
    animate();
}
</script>
</head>
<body>
  <canvas id="canvas" width="500" height="400"
    style="border: 1px solid #000000;"></canvas>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

https://codepen.io/forTheLoveOfCode/pen/wqdpeg

这就是你需要的吗? (链接到上面的codepen)。

var canvas = document.getElementById("canvas_id");
var context = canvas.getContext('2d');
var x=5;
var y=5;
var velocity = 10;
   
function move(){
   canvas.width = window.innerWidth;
   canvas.height = window.innerHeight;
   x =x + velocity
   if ((x+50)>canvas.width || x<0){
    	velocity *=-1;
   }
   draw()
}

function draw(){
   context.fillStyle = "#E80C7A";
   context.strokeStyle = "#000000";
   context.lineWidth = '3';
   context.fillRect(x, y, 50, 100);
   context.strokeRect(x, y, 50, 100);
}
setInterval(move, 100);
<html>
  <body>
    <canvas id = "canvas_id">
    </canvas>
  </body>
</html>

答案 1 :(得分:0)

这是一个带边界检测的解决方案

window.onload=function(){
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var x = 0;
    var y = 50;
    var width = 10;
    var height = 10;
    var speed = 10; // speed
    function animate() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillRect(x, y, width, height);
        if(
          (x >= 500 - width && speed > 0) || // going to the right and bound reached
          (x <= 0 && speed < 0) // going to the left and bound reached
          ) {
            speed *= -1; // inverting the direction
        }
        x += speed;
        setTimeout(animate, 33);
    }
    animate();
}
<canvas id="canvas" width="500" height="400"
    style="border: 1px solid #000000;"></canvas>

考虑使用requestAnimationFrame代替setTimeout来完成此类工作。