调整 HTML5 画布大小以适合窗口

2022-08-29 23:17:45

如何自动缩放HTML5元素以适应页面?<canvas>

例如,我可以通过将 and 属性设置为 100% 来获得缩放,但 a 不会缩放,不是吗?<div>heightwidth<canvas>


答案 1

我相信我已经找到了一个优雅的解决方案:

JavaScript

/* important! for alignment, you should make things
 * relative to the canvas' current width/height.
 */
function draw() {
  var ctx = (a canvas context);
  ctx.canvas.width  = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
  //...drawing code...
}

断续器

html, body {
  width:  100%;
  height: 100%;
  margin: 0;
}

到目前为止,还没有对我产生任何重大的负面性能影响。


答案 2

以下解决方案最适合我。由于我对编码相对较新,因此我喜欢在视觉上确认某些东西正在按照我期望的方式工作。我在以下网站上找到了它:http://htmlcheats.com/html/resize-the-html5-canvas-dyamically/

代码如下:

(function() {
  var
    // Obtain a reference to the canvas element using its id.
    htmlCanvas = document.getElementById('c'),
    // Obtain a graphics context on the canvas element for drawing.
    context = htmlCanvas.getContext('2d');

  // Start listening to resize events and draw canvas.
  initialize();

  function initialize() {
    // Register an event listener to call the resizeCanvas() function 
    // each time the window is resized.
    window.addEventListener('resize', resizeCanvas, false);
    // Draw canvas border for the first time.
    resizeCanvas();
  }

  // Display custom canvas. In this case it's a blue, 5 pixel 
  // border that resizes along with the browser window.
  function redraw() {
    context.strokeStyle = 'blue';
    context.lineWidth = '5';
    context.strokeRect(0, 0, window.innerWidth, window.innerHeight);
  }

  // Runs each time the DOM window resize event fires.
  // Resets the canvas dimensions to match window,
  // then draws the new borders accordingly.
  function resizeCanvas() {
    htmlCanvas.width = window.innerWidth;
    htmlCanvas.height = window.innerHeight;
    redraw();
  }
})();
html,
body {
  width: 100%;
  height: 100%;
  margin: 0px;
  border: 0;
  overflow: hidden;
  /*  Disable scrollbars */
  display: block;
  /* No floating content on sides */
}
<canvas id='c' style='position:absolute; left:0px; top:0px;'></canvas>

蓝色边框显示调整大小画布的边缘,并且始终沿着窗口的边缘,在所有4个侧面都可见,对于上述其他一些答案,情况并非如此。希望它有帮助。