【问题标题】:margin right not working on canvas html5 and trouble with scroll bar removal边距在画布 html5 上不起作用,并且滚动条删除有问题
【发布时间】:2019-11-27 17:57:10
【问题描述】:

我有以下画布:

Codepen link

我想要的:画布两边的边距相等,没有任何水平滚动条。

问题margin-right 属性不起作用。我已经看到了一些通过指定固定宽度来解决此问题的解决方案,但在我的情况下我不能有固定宽度。我希望我的画布根据窗口的大小调整其宽度高度。

下面的 Javascript 会处理这个问题:

window.addEventListener('resize' , resizeCanvas , false);

function resizeCanvas(){
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight/1.2;
}

那么有不同的解决方案吗?

对于溢出问题,如果我将overflow-x: hidden 放在body 中,那么只有滚动条会消失,但问题仍然存在。画布仍然延伸到屏幕之外,因此画布的右边框不再可见。 See here

这是我的代码:

HTML

<body onload="start()">
    <canvas id="myCanvas"></canvas>
</body>

CSS

body{

}

canvas{

    border: 1px solid black;
    border-radius: 5px;
    background-color: #fff;

    margin: auto 50px auto 50px; /* works for left margin but not for right */

}

谢谢!

另一件事:

我没有为画布设置width: 100%,因为它会扭曲其中的内容。

【问题讨论】:

  • 您故意使画布与窗口一样宽。在顶部添加边距会使文档比窗口宽。
  • 你是说下面这行有问题吗? margin: auto 50px auto 50px; ?如果是这样,我也尝试删除 margin-top 但没有任何改变。 codepen.io/swagnikd/full/VWbNgV
  • 我的意思是:canvas.width = window.innerWidth; 是问题所在。如果您不想要水平滚动条而是在侧面有边距,那么您显然不能使画布与窗口一样宽...
  • 我明白了。谢谢,克里斯!

标签: javascript css html canvas


【解决方案1】:

正如克里斯所说,您需要将canvaswidth 设置为低于页面的整个宽度:

canvas.width = window.innerWidth - 100;

请注意,您需要考虑画布的border-width,并且在您的代码笔中,主体也有8px 的边距:

canvas.width = window.innerWidth - 118;

【讨论】:

    【解决方案2】:

    CSS calc() 方法是你所需要的。只需从 100% 中减去边距,即可获得所需的结果。请参阅下面的演示。 CSS calc() reference

    function start() {
    
      var canvas = document.getElementById('myCanvas');
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight / 1.2;
      var ctx = canvas.getContext('2d');
    
      function rand(min, max) {
        return parseInt(Math.random() * (max - min + 1), 10) + min;
      }
    
      function get_random_color() {
        var h = rand(1, 360);
        var s = rand(30, 100);
        var l = rand(30, 70);
        return 'hsl(' + h + ',' + s + '%,' + l + '%)';
      }
    
      function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
      }
    
      var balls = [];
      var ballCount = getRandomInt(2, 10);
      //document.getElementById('ballCountInfo').innerHTML = ballCount;
      //document.getElementById('box').innerHTML = ballCount;
      var startpointX = 100;
      var startpointY = 50;
    
      for (var i = 0; i < ballCount; i++) {
    
        var randValue = getRandomInt(20, 30);
        balls.push({
          x: startpointX,
          y: startpointY,
          vx: getRandomInt(3, 3) * direction(),
          vy: getRandomInt(1, 1) * direction(),
          radius: randValue,
          mass: randValue,
          color: get_random_color(),
    
          draw: function() {
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
            ctx.closePath();
            ctx.fillStyle = this.color;
            ctx.fill();
          }
        });
    
        startpointX = startpointX + 50;
        startpointY = startpointY + 40;
      }
    
    
      function direction() {
        var chosenValue = Math.random() < 0.5 ? 1 : -1;
        return chosenValue;
      }
    
      function draw() {
    
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        for (var i = 0; i < ballCount; i++) {
    
          balls[i].draw();
          balls[i].x += balls[i].vx;
          balls[i].y += balls[i].vy;
    
          if ((balls[i].y + balls[i].vy + balls[i].radius) > canvas.height || (balls[i].y + balls[i].vy - balls[i].radius) < 0) {
            balls[i].vy = -balls[i].vy;
          }
          if ((balls[i].x + balls[i].vx + balls[i].radius) > canvas.width || (balls[i].x + balls[i].vx - balls[i].radius) < 0) {
            balls[i].vx = -balls[i].vx;
          }
        }
    
        //		onBoxTouched();
    
        //collision check
        for (var i = 0; i < ballCount; i++) {
          for (var j = i + 1; j < ballCount; j++) {
    
            var distance = Math.sqrt(
              (balls[i].x - balls[j].x) * (balls[i].x - balls[j].x) +
              (balls[i].y - balls[j].y) * (balls[i].y - balls[j].y)
            );
    
            if (distance < (balls[i].radius + balls[j].radius)) {
    
              var ax = (balls[i].vx * (balls[i].mass - balls[j].mass) + (2 * balls[j].mass * balls[j].vx)) / (balls[i].mass + balls[j].mass);
              var ay = (balls[i].vy * (balls[i].mass - balls[j].mass) + (2 * balls[j].mass * balls[j].vy)) / (balls[i].mass + balls[j].mass);
              balls[j].vx = (balls[j].vx * (balls[j].mass - balls[i].mass) + (2 * balls[i].mass * balls[i].vx)) / (balls[i].mass + balls[j].mass);
              balls[j].vy = (balls[j].vy * (balls[j].mass - balls[i].mass) + (2 * balls[i].mass * balls[i].vy)) / (balls[i].mass + balls[j].mass);
              balls[i].vx = ax;
              balls[i].vy = ay;
            }
          }
        }
    
        raf = window.requestAnimationFrame(draw);
      }
    
    
      function onBoxTouched() {
    
        for (var i = 0; i < ballCount; i++) {
    
          if (balls[i].x + balls[i].radius > 600 && balls[i].x + balls[i].radius < 750 &&
            balls[i].y + balls[i].radius > 200 && balls[i].y + balls[i].radius < 350) {
    
            //var ele = document.getElementById("box");
            ele.style.backgroundColor = balls[i].color;
    
            balls.splice(i, 1);
            ballCount = ballCount - 1;
    
            if (ballCount == 0) {
              ele.style.fontSize = "x-large";
              ele.innerHTML = "Over";
            } else {
              ele.innerHTML = ballCount;
            }
    
            //document.getElementById('ballCountInfo').innerHTML=" "+ballCount;
          }
        }
      }
    
      window.requestAnimationFrame(draw);
    
      window.addEventListener('resize', resizeCanvas, false);
    
      function resizeCanvas() {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight / 1.2;
      }
    
    
    
    }
    * {}
    
    html,
    body {}
    
    canvas {
      border: 1px solid black;
      border-radius: 5px;
      background-color: #fff;
      width: calc(100% - 40px);
      /*substract the total margin from 100% and will automoatically adjuts accordint to your need*/
      margin: auto 20px auto 20px;
      /* works for left margin but not for right */
    }
    
    #box {
      width: 150px;
      height: 150px;
      background-color: plum;
      border-radius: 5px;
      position: absolute;
      top: 200px;
      left: 600px;
      font-size: 72px;
      font-weight: bold;
      color: white;
      line-height: 150px;
      text-align: center;
    }
    
    #info {
      float: left;
      font-size: 24px;
      color: #6D8390;
      margin-top: 20px;
    }
    <body onload="start()">
      <canvas id="myCanvas"></canvas>
    </body>

    希望对你有帮助:)

    【讨论】:

      【解决方案3】:

      不要乱用边距,只需更改画布的宽度并将其居中即可。

      CSS

      canvas {
        border: 1px solid black;
        border-radius: 5px;
        background-color: #fff;
        width: 90%!important;
      }
      

      HTML

      <body onload="start()">
        <center>
          <canvas id="myCanvas"></canvas>
        </center>
      </body>
      

      https://codepen.io/anon/pen/GEmLPL

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-06
        • 1970-01-01
        • 2018-09-26
        • 2011-12-18
        相关资源
        最近更新 更多