画布如何用窗口调整大小?

时间:2019-10-01 15:23:29

标签: javascript bootstrap-4 anime.js

我刚刚开始学习Web开发,但我一直遇到问题。

我尝试使用一个画布作为标题站点。我正在尝试使用这个:

https://codepen.io/towc/pen/mJzOWJ

但是不幸的是,即使画布位于div中,当我调整窗口大小时,画布也无法正常工作,并且画布比以前更高。

我已经尝试将画布放在适当的div中,并初始化height = 100%和width = 100%

HEADER

这是我标头的代码

<header class="masthead">
      <canvas id="c" height="100%" width="100%"></canvas>
    <div class="overlay"></div>

    <div class="container">

      <div class="row"> 

        <div class="col-lg-8 col-md-10 mx-auto">

          <div class="site-heading">

            <h1>My website</h1>
            <span class="subheading">Etudiant ingénieur <br> Artificial Intelligence</span>
          </div>
        </div>
      </div>
    </div>
  </header>

CSS PART

header.masthead {

  margin-bottom: 30px;
  background: no-repeat center center;
  background-color: #868e96;
  background-attachment: scroll;
  position: relative;
  background-size: cover;

}

header.masthead .overlay {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background-color: #212529;
  opacity: 0.5;
}

header.masthead .page-heading,
header.masthead .post-heading,
header.masthead .site-heading {
  padding: 100px 0 50px;
  color: white;
}

@media only screen and (min-width: 768px) {
  header.masthead .page-heading,
  header.masthead .post-heading,
  header.masthead .site-heading {
    padding: 50px 0;
  }
}

header.masthead .page-heading,
header.masthead .site-heading {
  text-align: center;
}

所以我想调整我在调整窗口大小之前显示给您的画布的大小,并使其达到横幅的大小。

感谢您的建议,我敢肯定它很容易管理。

1 个答案:

答案 0 :(得分:0)

我最终将其修复。

我是用javascript编写的脚本上完成的

var canvas = document.querySelector('c');
fitToContainer(canvas);

function fitToContainer(canvas){

  c.style.width ='100%';
  c.style.height='100%';
  c.width  = c.offsetWidth;
  c.height = c.offsetHeight;
}