简体   繁体   English

停止动画元素离开画布

[英]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/ 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 . 您正在寻找的方法称为“冲突检测” 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". 通常,通过反转动画方向来产生“反弹”效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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