简体   繁体   中英

Stop animated element leaving the canvas

I'm trying to stop the element leaving the canvas. Whether this resets the loop, or just prevents it going any further -- I'm not sure. What is a common method for preventing the element leaving the canvas?

I've got the following code:

http://jsfiddle.net/tmyie/R5wx8/2/

var canvas = document.getElementById('canvas'),
    c = canvas.getContext('2d'),
     x = 10,
        y = 15;
function move() {
   c.clearRect(0, 0, 500, 300);
    c.fillRect(x, y, 5, 5),
    c.fillRect(x, y, 15, 15);
    x++;
    y++;
}

setInterval(move, 300);

You need to use a condition:

function move() {
    c.clearRect(0, 0, 500, 300);
    c.fillRect(x, y, 5, 5),
    c.fillRect(x, y, 15, 15);
    if (x < canvas.width - 10) x++;  /// 10 being an arbitrary value
    if (y < canvas.height - 10) y++;
}

The same way you can reset your loop:

x++;
if (x > canvas.width) x = 0;

The arbitrary value in the example is meant as a placeholder for a real object width which you need to base on the object's actual dimension.

The method you are looking for is known as "collision detection" wiki .

Basically it involves a few calculations. You are going to have to know the bounds of the area that could be collided with by the object.

You are also going to make sure you calculate the size of the object.

If the position of the object + its size is greater than the location of a boundary then there was a collision. Usually it is handled by reversing that direction of animation producing the effect of a "bounce".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM