【问题标题】:How to make the element the height of the browser window? [duplicate]如何使元素成为浏览器窗口的高度? [复制]
【发布时间】:2021-02-16 01:13:54
【问题描述】:

我有以下代码:

var canvas = document.getElementById('nokey'),
   can_w = parseInt(canvas.getAttribute('width')),
   can_h = parseInt(canvas.getAttribute('height')),
   ctx = canvas.getContext('2d');

// console.log(typeof can_w);

var ball = {
      x: 0,
      y: 0,
      vx: 0,
      vy: 0,
      r: 0,
      alpha: 1,
      phase: 0
   },
   ball_color = {
       r: 207,
       g: 255,
       b: 4
   },
   R = 2,
   balls = [],
   alpha_f = 0.03,
   alpha_phase = 0,
    
// Line
   link_line_width = 0.8,
   dis_limit = 260,
   add_mouse_point = true,
   mouse_in = false,
   mouse_ball = {
      x: 0,
      y: 0,
      vx: 0,
      vy: 0,
      r: 0,
      type: 'mouse'
   };

// Random speed
function getRandomSpeed(pos){
    var  min = -1,
       max = 1;
    switch(pos){
        case 'top':
            return [randomNumFrom(min, max), randomNumFrom(0.1, max)];
            break;
        case 'right':
            return [randomNumFrom(min, -0.1), randomNumFrom(min, max)];
            break;
        case 'bottom':
            return [randomNumFrom(min, max), randomNumFrom(min, -0.1)];
            break;
        case 'left':
            return [randomNumFrom(0.1, max), randomNumFrom(min, max)];
            break;
        default:
            return;
            break;
    }
}
function randomArrayItem(arr){
    return arr[Math.floor(Math.random() * arr.length)];
}
function randomNumFrom(min, max){
    return Math.random()*(max - min) + min;
}
console.log(randomNumFrom(0, 10));
// Random Ball
function getRandomBall(){
    var pos = randomArrayItem(['top', 'right', 'bottom', 'left']);
    switch(pos){
        case 'top':
            return {
                x: randomSidePos(can_w),
                y: -R,
                vx: getRandomSpeed('top')[0],
                vy: getRandomSpeed('top')[1],
                r: R,
                alpha: 1,
                phase: randomNumFrom(0, 10)
            }
            break;
        case 'right':
            return {
                x: can_w + R,
                y: randomSidePos(can_h),
                vx: getRandomSpeed('right')[0],
                vy: getRandomSpeed('right')[1],
                r: R,
                alpha: 1,
                phase: randomNumFrom(0, 10)
            }
            break;
        case 'bottom':
            return {
                x: randomSidePos(can_w),
                y: can_h + R,
                vx: getRandomSpeed('bottom')[0],
                vy: getRandomSpeed('bottom')[1],
                r: R,
                alpha: 1,
                phase: randomNumFrom(0, 10)
            }
            break;
        case 'left':
            return {
                x: -R,
                y: randomSidePos(can_h),
                vx: getRandomSpeed('left')[0],
                vy: getRandomSpeed('left')[1],
                r: R,
                alpha: 1,
                phase: randomNumFrom(0, 10)
            }
            break;
    }
}
function randomSidePos(length){
    return Math.ceil(Math.random() * length);
}

// Draw Ball
function renderBalls(){
    Array.prototype.forEach.call(balls, function(b){
       if(!b.hasOwnProperty('type')){
           ctx.fillStyle = 'rgba('+ball_color.r+','+ball_color.g+','+ball_color.b+','+b.alpha+')';
           ctx.beginPath();
           ctx.arc(b.x, b.y, R, 0, Math.PI*2, true);
           ctx.closePath();
           ctx.fill();
       }
    });
}

// Update balls
function updateBalls(){
    var new_balls = [];
    Array.prototype.forEach.call(balls, function(b){
        b.x += b.vx;
        b.y += b.vy;
        
        if(b.x > -(50) && b.x < (can_w+50) && b.y > -(50) && b.y < (can_h+50)){
           new_balls.push(b);
        }
        
        // alpha change
        b.phase += alpha_f;
        b.alpha = Math.abs(Math.cos(b.phase));
        // console.log(b.alpha);
    });
    
    balls = new_balls.slice(0);
}

// loop alpha
function loopAlphaInf(){
    
}

// Draw lines
function renderLines(){
    var fraction, alpha;
    for (var i = 0; i < balls.length; i++) {
        for (var j = i + 1; j < balls.length; j++) {
           
           fraction = getDisOf(balls[i], balls[j]) / dis_limit;
            
           if(fraction < 1){
               alpha = (1 - fraction).toString();

               ctx.strokeStyle = 'rgba(150,150,150,'+alpha+')';
               ctx.lineWidth = link_line_width;
               
               ctx.beginPath();
               ctx.moveTo(balls[i].x, balls[i].y);
               ctx.lineTo(balls[j].x, balls[j].y);
               ctx.stroke();
               ctx.closePath();
           }
        }
    }
}

// calculate distance between two points
function getDisOf(b1, b2){
    var  delta_x = Math.abs(b1.x - b2.x),
       delta_y = Math.abs(b1.y - b2.y);
    
    return Math.sqrt(delta_x*delta_x + delta_y*delta_y);
}

// add balls if there a little balls
function addBallIfy(){
    if(balls.length < 20){
        balls.push(getRandomBall());
    }
}

// Render
function render(){
    ctx.clearRect(0, 0, can_w, can_h);
    
    renderBalls();
    
    renderLines();
    
    updateBalls();
    
    addBallIfy();
    
    window.requestAnimationFrame(render);
}

// Init Balls
function initBalls(num){
    for(var i = 1; i <= num; i++){
        balls.push({
            x: randomSidePos(can_w),
            y: randomSidePos(can_h),
            vx: getRandomSpeed('top')[0],
            vy: getRandomSpeed('top')[1],
            r: R,
            alpha: 1,
            phase: randomNumFrom(0, 10)
        });
    }
}
// Init Canvas
function initCanvas(){
    canvas.setAttribute('width', window.innerWidth);
    canvas.setAttribute('height', window.innerHeight);
    
    can_w = parseInt(canvas.getAttribute('width'));
    can_h = parseInt(canvas.getAttribute('height'));
}
window.addEventListener('resize', function(e){
    console.log('Window Resize...');
    initCanvas();
});

function goMovie(){
    initCanvas();
    initBalls(30);
    window.requestAnimationFrame(render);
}
goMovie();

// Mouse effect
canvas.addEventListener('mouseenter', function(){
    console.log('mouseenter');
    mouse_in = true;
    balls.push(mouse_ball);
});
canvas.addEventListener('mouseleave', function(){
    console.log('mouseleave');
    mouse_in = false;
    var new_balls = [];
    Array.prototype.forEach.call(balls, function(b){
        if(!b.hasOwnProperty('type')){
            new_balls.push(b);
        }
    });
    balls = new_balls.slice(0);
});
canvas.addEventListener('mousemove', function(e){
    var e = e || window.event;
    mouse_ball.x = e.pageX;
    mouse_ball.y = e.pageY;
    // console.log(mouse_ball);
});
*{
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
body{
    height: 100%;
    margin: 0;
    padding: 0;
    background-color: transparent;
    overflow: hidden;
}
canvas{
  z-index: -1;
  
  position: absolute;
    background-color: transparent;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <canvas id="nokey" width="800" height="800">
</canvas>

    <script src="script.js"></script>
  </body>
</html>

我希望动画是浏览器窗口的高度,但问题是我对内容的每个部分都有不同的部分,每个部分都用&lt;section&gt; and &lt;/section&gt; 分隔,所以有没有办法让动画成为整个浏览器窗口的高度?我尝试将高度更改为 100%,但它不起作用。另外,我应该把 HTML 代码放在我的文件中吗?就像在顶部的某个地方?谢谢

【问题讨论】:

    标签: javascript html jquery css animation


    【解决方案1】:

    设置为视口高度的 100% 可能会起作用。

    var canvas = document.getElementById('nokey'),
       can_w = parseInt(canvas.getAttribute('width')),
       can_h = parseInt(canvas.getAttribute('height')),
       ctx = canvas.getContext('2d');
    
    // console.log(typeof can_w);
    
    var ball = {
          x: 0,
          y: 0,
          vx: 0,
          vy: 0,
          r: 0,
          alpha: 1,
          phase: 0
       },
       ball_color = {
           r: 207,
           g: 255,
           b: 4
       },
       R = 2,
       balls = [],
       alpha_f = 0.03,
       alpha_phase = 0,
        
    // Line
       link_line_width = 0.8,
       dis_limit = 260,
       add_mouse_point = true,
       mouse_in = false,
       mouse_ball = {
          x: 0,
          y: 0,
          vx: 0,
          vy: 0,
          r: 0,
          type: 'mouse'
       };
    
    // Random speed
    function getRandomSpeed(pos){
        var  min = -1,
           max = 1;
        switch(pos){
            case 'top':
                return [randomNumFrom(min, max), randomNumFrom(0.1, max)];
                break;
            case 'right':
                return [randomNumFrom(min, -0.1), randomNumFrom(min, max)];
                break;
            case 'bottom':
                return [randomNumFrom(min, max), randomNumFrom(min, -0.1)];
                break;
            case 'left':
                return [randomNumFrom(0.1, max), randomNumFrom(min, max)];
                break;
            default:
                return;
                break;
        }
    }
    function randomArrayItem(arr){
        return arr[Math.floor(Math.random() * arr.length)];
    }
    function randomNumFrom(min, max){
        return Math.random()*(max - min) + min;
    }
    console.log(randomNumFrom(0, 10));
    // Random Ball
    function getRandomBall(){
        var pos = randomArrayItem(['top', 'right', 'bottom', 'left']);
        switch(pos){
            case 'top':
                return {
                    x: randomSidePos(can_w),
                    y: -R,
                    vx: getRandomSpeed('top')[0],
                    vy: getRandomSpeed('top')[1],
                    r: R,
                    alpha: 1,
                    phase: randomNumFrom(0, 10)
                }
                break;
            case 'right':
                return {
                    x: can_w + R,
                    y: randomSidePos(can_h),
                    vx: getRandomSpeed('right')[0],
                    vy: getRandomSpeed('right')[1],
                    r: R,
                    alpha: 1,
                    phase: randomNumFrom(0, 10)
                }
                break;
            case 'bottom':
                return {
                    x: randomSidePos(can_w),
                    y: can_h + R,
                    vx: getRandomSpeed('bottom')[0],
                    vy: getRandomSpeed('bottom')[1],
                    r: R,
                    alpha: 1,
                    phase: randomNumFrom(0, 10)
                }
                break;
            case 'left':
                return {
                    x: -R,
                    y: randomSidePos(can_h),
                    vx: getRandomSpeed('left')[0],
                    vy: getRandomSpeed('left')[1],
                    r: R,
                    alpha: 1,
                    phase: randomNumFrom(0, 10)
                }
                break;
        }
    }
    function randomSidePos(length){
        return Math.ceil(Math.random() * length);
    }
    
    // Draw Ball
    function renderBalls(){
        Array.prototype.forEach.call(balls, function(b){
           if(!b.hasOwnProperty('type')){
               ctx.fillStyle = 'rgba('+ball_color.r+','+ball_color.g+','+ball_color.b+','+b.alpha+')';
               ctx.beginPath();
               ctx.arc(b.x, b.y, R, 0, Math.PI*2, true);
               ctx.closePath();
               ctx.fill();
           }
        });
    }
    
    // Update balls
    function updateBalls(){
        var new_balls = [];
        Array.prototype.forEach.call(balls, function(b){
            b.x += b.vx;
            b.y += b.vy;
            
            if(b.x > -(50) && b.x < (can_w+50) && b.y > -(50) && b.y < (can_h+50)){
               new_balls.push(b);
            }
            
            // alpha change
            b.phase += alpha_f;
            b.alpha = Math.abs(Math.cos(b.phase));
            // console.log(b.alpha);
        });
        
        balls = new_balls.slice(0);
    }
    
    // loop alpha
    function loopAlphaInf(){
        
    }
    
    // Draw lines
    function renderLines(){
        var fraction, alpha;
        for (var i = 0; i < balls.length; i++) {
            for (var j = i + 1; j < balls.length; j++) {
               
               fraction = getDisOf(balls[i], balls[j]) / dis_limit;
                
               if(fraction < 1){
                   alpha = (1 - fraction).toString();
    
                   ctx.strokeStyle = 'rgba(150,150,150,'+alpha+')';
                   ctx.lineWidth = link_line_width;
                   
                   ctx.beginPath();
                   ctx.moveTo(balls[i].x, balls[i].y);
                   ctx.lineTo(balls[j].x, balls[j].y);
                   ctx.stroke();
                   ctx.closePath();
               }
            }
        }
    }
    
    // calculate distance between two points
    function getDisOf(b1, b2){
        var  delta_x = Math.abs(b1.x - b2.x),
           delta_y = Math.abs(b1.y - b2.y);
        
        return Math.sqrt(delta_x*delta_x + delta_y*delta_y);
    }
    
    // add balls if there a little balls
    function addBallIfy(){
        if(balls.length < 20){
            balls.push(getRandomBall());
        }
    }
    
    // Render
    function render(){
        ctx.clearRect(0, 0, can_w, can_h);
        
        renderBalls();
        
        renderLines();
        
        updateBalls();
        
        addBallIfy();
        
        window.requestAnimationFrame(render);
    }
    
    // Init Balls
    function initBalls(num){
        for(var i = 1; i <= num; i++){
            balls.push({
                x: randomSidePos(can_w),
                y: randomSidePos(can_h),
                vx: getRandomSpeed('top')[0],
                vy: getRandomSpeed('top')[1],
                r: R,
                alpha: 1,
                phase: randomNumFrom(0, 10)
            });
        }
    }
    // Init Canvas
    function initCanvas(){
        canvas.setAttribute('width', window.innerWidth);
        canvas.setAttribute('height', window.innerHeight);
        
        can_w = parseInt(canvas.getAttribute('width'));
        can_h = parseInt(canvas.getAttribute('height'));
    }
    window.addEventListener('resize', function(e){
        console.log('Window Resize...');
        initCanvas();
    });
    
    function goMovie(){
        initCanvas();
        initBalls(30);
        window.requestAnimationFrame(render);
    }
    goMovie();
    
    // Mouse effect
    canvas.addEventListener('mouseenter', function(){
        console.log('mouseenter');
        mouse_in = true;
        balls.push(mouse_ball);
    });
    canvas.addEventListener('mouseleave', function(){
        console.log('mouseleave');
        mouse_in = false;
        var new_balls = [];
        Array.prototype.forEach.call(balls, function(b){
            if(!b.hasOwnProperty('type')){
                new_balls.push(b);
            }
        });
        balls = new_balls.slice(0);
    });
    canvas.addEventListener('mousemove', function(e){
        var e = e || window.event;
        mouse_ball.x = e.pageX;
        mouse_ball.y = e.pageY;
        // console.log(mouse_ball);
    });
    
    // Resize the canvas
    
    (function() {
        var canvas = document.getElementById('canvas'),
                context = canvas.getContext('2d');
    
        // resize the canvas to fill browser window dynamically
        window.addEventListener('resize', resizeCanvas, false);
    
        function resizeCanvas() {
                canvas.width = window.innerWidth;
                canvas.height = window.innerHeight;
    
                /**
                 * Your drawings need to be inside this function otherwise they will be reset when 
                 * you resize the browser window and the canvas goes will be cleared.
                 */
                drawStuff(); 
        }
        resizeCanvas();
    
        function drawStuff() {
                // do your drawing stuff here
        }
    })();
    *{
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
    }
    body{
        height: 100vh;
        margin: 0;
        padding: 0;
        background-color: transparent;
        overflow: hidden;
    }
    canvas{
      z-index: -1;
      position: absolute;
      background-color: transparent;
    }
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>repl.it</title>
        <link href="style.css" rel="stylesheet" type="text/css" />
      </head>
      <body>
        <canvas id="nokey">
    </canvas>
    
        <script src="script.js"></script>
      </body>
    </html>

    【讨论】:

    • HTML 代码是否位于网站顶部?如果是,我应该把它放在哪里?
    • 这取决于你是否在内联做所有事情
    • Wdym?为了让动画适用于整个网站,我应该把 HTML 代码放在一个特定的地方吗?
    【解决方案2】:

    窗口对象有一个调整大小的方法,您可以使用它来设置为局部变量。

    使用此方法,您可以将元素的高度设置为始终为视口的高度。

    let getWindowDimensions = {
      width: 0,
      height: 0
    };
    
    const handleResize = () => {
        getWindowDimensions.width = window.innerWidth;
        getWindowDimensions.height = window.innerHeight;
      };
    
    window.addEventListener('resize', handleResize());
    
    
    function myFunc() { document.getElementById("makeWindowHeight").style.height = `${getWindowDimensions.height}px`;
    }
     
    myFunc();
    
    console.log(getWindowDimensions);
    .test {
      background-color: blue;
      width: 50px;
    }
    &lt;div class="test" id="makeWindowHeight"&gt;&lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-07
      • 1970-01-01
      • 2016-08-16
      相关资源
      最近更新 更多