3

这个主题已被多次询问和回答,但我尝试了几乎所有给出的解决方案,但没有解决我的问题。我在 div 中有一个方形画布元素,它延伸到覆盖所有可用屏幕。当屏幕处于横向模式时,我们希望用户垂直滚动画布绘图以查看它。这完美地工作。当屏幕调整大小或将方向更改为纵向时,我们希望用户水平滚动画布绘图。这也可以按预期工作。但是一旦用户调整屏幕大小(甚至调整一个像素),就会出现一个垂直滚动条,它只会将画布绘图移动几个像素。通过重新加载页面(保持相同大小),垂直滚动条消失了,很奇怪。同样在纵向和横向之间的过渡中,存在浏览器不稳定。

我已经花了一个周末尝试各种方法来解决这个问题,并编写了一个小程序来显示滚动条的奇怪外观。请帮忙。CSS 不是我的强项。

var canvasSize = 0;
var ctx;
var canvas;

function init() {
  canvas = document.getElementById('myCanvas');
  if (canvas.getContext) {
    ctx = canvas.getContext("2d");
    // I add listeners to dynamically redraw the canvas when the user changes orientation/size
    window.addEventListener('resize', resizeCanvas, false);
    window.addEventListener('orientationchange', resizeCanvas, false);
    resizeCanvas();
  } else {
    alert("ERROR:  APPLICATION CANNOT RUN ON THIS DEVICE");
    return;
  }
}

function resizeCanvas() {
  let viewPortWidth = document.getElementById("radarScreen").clientWidth;
  let viewPortHeight = document.getElementById("radarScreen").clientHeight;
  let portaitMode = (viewPortHeight > viewPortWidth) ? true : false;

  if (portaitMode) {
    // IN PORTAIT MODE I WANT TO HAVE HORIZONTAL SCROLLBAR TO VIEW THE HIDDEN PART OF THE CANVAS
    //  UNFORTUNATELLY A GET ALSO A VERTICAL SCROLLBAR THAT MOVES THE CANVAS A FEW PIXELS UP/DOWN
    console.log("portait mode ON");
    canvas.width = viewPortHeight;
    canvas.height = viewPortHeight;
  } else { /* landscapeMode */
    //  IN LANDSCAPE MODE I WANT TO HAVE A VERTICAL SCROLLBAR TO VIEW THE HIDDEN PART OF THE CANVAS
    //  UNFORTUNATELLY A GET ALSO A HORIZONTAL SCROLLBAR THAT MOVES THE CANVAS A FEW PIXELS UP/DOWN     
    canvas.width = viewPortWidth;
    canvas.height = viewPortWidth;
  }
  // INSPECTING THE HTML GIVES NO CLEW WHERE THESE SCROLLBARS ARE CREATED
  canvasSize = canvas.width;

  // now we need to redraw the canvas
  ctx.clearRect(0, 0, canvasSize, canvasSize);

  ctx.strokeStyle = "black";
  ctx.lineWidth = 0.2 * canvasSize;
  ctx.beginPath();
  ctx.rect(0, 0, canvasSize, canvasSize);
  ctx.stroke();

  ctx.font = "80px Arial";
  ctx.fillStyle = "red";
  ctx.textAlign = "center";
  if (portaitMode) ctx.fillText("Portrait ", canvasSize / 2, canvasSize / 4);
  else ctx.fillText("Landscape ", canvasSize / 2, canvasSize / 4);
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  height: 100vh;
}

#radarScreen {
  display: block;
  height: 100%;
  width: 100%;
}

canvas {
  background-color: #777;
}
<body onload='init()'>
  <!-- RADAR SCREEN CANVAS SECTION -->
  <div id="radarScreen">
    <canvas id="myCanvas"></canvas>
  </div>
</body>

4

1 回答 1

0

我不确定是什么导致了滚动;栏出现,但这是一种似乎可以解决问题的变通方法。

#radarScreen {
  display: block;
  height: 100%;
  width: calc(100% - 1px);
}
于 2021-12-06T00:27:12.537 回答