在Bootstrap网站中包含动态/移动背景

Including a dynamic/moving background in Bootstrap website

本文关键字:移动 背景 动态 包含 Bootstrap 网站      更新时间:2023-09-26

如何制作动画背景(javascript/css)作为网站的主体背景(或等效背景)?我可以将它放在div中并使其工作,但无法将其设置为背景。注意:我使用的是引导程序。

我假设我只是在javascript中选择了正文,但我可能做错了。类似于:canvas = document.body,然后移除"myHolder",因为支架就是主体。

下面是我的HTMLdiv,用于显示内容。(我知道把它设置为背景是错误的,但这是我能让它显示的唯一方法)

<div id="myHolder">
<canvas id="myAnimation"></canvas>
</div>

下面是我的javascript(与上面的canvas/div相关的部分):

initHeader() {
        width = window.innerWidth;
        height = window.innerHeight;
        target = {x: width/2, y: height/2};
        largeHeader = document.getElementById('myHolder');
        largeHeader.style.height = height+'px';
        canvas = document.getElementById('myAnimation');
        canvas.width = width;
        canvas.height = height;
        ctx = canvas.getContext('2d');
}
function resize() {
        width = window.innerWidth;
        height = window.innerHeight;
        largeHeader.style.height = height+'px';
        canvas.width = width;
        canvas.height = height;
    }

更新:我的页面现在包含以下代码:动画显示为背景,但其他div仍被向下推。但是,背景正确地显示在其他div后面。

    <style>
    #myAnimation {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }
    </style>
    <div id="myHolder">
    <canvas id="myAnimation" width="100%" height="100%"></canvas>
    </div>
....page content...

幸运的是,这只是一个CSS更改!

#myAnimation {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -100; //Put your background behind the rest of your content
}

请注意,这将拉伸画布,因此如果要避免这种情况,则需要将宽度和高度设置为100%作为属性。

<canvas id="myAnimation" width="100%" height="100%">