【问题标题】:How to set new X / Y coordinates when a triangle leaves the canvas window?当三角形离开画布窗口时如何设置新的 X / Y 坐标?
【发布时间】:2014-01-02 07:15:34
【问题描述】:

此刻画布创建了 15 个以不同速度移动的三角形。当其中一个离开画布窗口时:

if(p.x >= W){
p.x = -300;
//Set new y coordinates
}

之后它从头开始,所以它是一个循环。问题是,三角形从它在开始时设置的相同 y 坐标开始。如何说三角形离开窗口时应该有新的 y 坐标?

    window.onload = function () {

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var W = canvas.width = window.innerWidth;
var H = canvas.height = window.innerHeight;

var r = Math.floor(Math.random()*20);

reqAnimFrame = window.requestAnimationFrame ||
               window.mozRequestAnimationFrame    ||
               window.webkitRequestAnimationFrame ||
               window.msRequestAnimationFrame     ||
               window.oRequestAnimationFrame;

var mp = 15; //max particles
var particles = [];
    for(var i = 0; i < mp; i++)
    {
        particles.push({
            x: Math.floor(Math.random()*W), //x-coordinate
            y: Math.floor(Math.random()*H), //y-coordinate
            d: Math.floor(Math.random()*(mp - 1) + 1) //density
        })
        console.log("again");
    }



function animate() {

    reqAnimFrame(animate);
    for(var i = 0; i < mp; i++)
        {
            var p = particles[i];
            p.x += p.d;

            if(p.x >= W){
                p.x = -300;
                //Give the triangle new y coordinates
            }
            draw();
        }

}

function draw() {
    ctx.clearRect(0, 0, W, H);
    ctx.fillStyle = "rgba(0,204,142,1";
    ctx.beginPath();
    for(var i = 0; i < mp; i++)
        {
            var p = particles[i];
            ctx.moveTo(p.x,p.y);
            ctx.lineTo(p.x + 150, p.y + (-180));
            ctx.lineTo(p.x + 300, p.y);
        }
    ctx.fill();

}
    animate();
};//onload function

【问题讨论】:

    标签: javascript html animation canvas random


    【解决方案1】:

    要在三角形离开窗口后设置它的 y 坐标,您需要做的就是重用代码 p.x = -300; 并为 y 坐标自定义它。

    例子:

    if(p.x >= W){
        p.x = -300;
        p.y = -300; //Or whatever you want it to be
    }
    

    现在,我假设您可能想要一个新的 随机 y 坐标。如果这样做,请在此处将 p.y = -300; 替换为 p.y = Math.floor(Math.random()*H);

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-05
      • 2011-07-27
      • 2011-11-13
      • 2021-06-28
      • 1970-01-01
      • 2021-05-14
      • 2022-01-12
      • 2010-11-14
      相关资源
      最近更新 更多