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

例如,我可以得到一个<div>通过设置高度和宽度属性为100%缩放,但一个<canvas>不会缩放,会吗?


当前回答

我认为这正是我们应该做的:http://www.html5rocks.com/en/tutorials/casestudies/gopherwoord-studios-resizing-html5-games/

function resizeGame() {
    var gameArea = document.getElementById('gameArea');
    var widthToHeight = 4 / 3;
    var newWidth = window.innerWidth;
    var newHeight = window.innerHeight;
    var newWidthToHeight = newWidth / newHeight;

    if (newWidthToHeight > widthToHeight) {
        newWidth = newHeight * widthToHeight;
        gameArea.style.height = newHeight + 'px';
        gameArea.style.width = newWidth + 'px';
    } else {
        newHeight = newWidth / widthToHeight;
        gameArea.style.width = newWidth + 'px';
        gameArea.style.height = newHeight + 'px';
    }

    gameArea.style.marginTop = (-newHeight / 2) + 'px';
    gameArea.style.marginLeft = (-newWidth / 2) + 'px';

    var gameCanvas = document.getElementById('gameCanvas');
    gameCanvas.width = newWidth;
    gameCanvas.height = newHeight;
}

window.addEventListener('resize', resizeGame, false);
window.addEventListener('orientationchange', resizeGame, false);

其他回答

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

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...
}

CSS

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

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

使用jQuery,您可以跟踪窗口调整大小和改变画布的宽度使用jQuery以及。

就像这样

$(window).resize(function() { $ (" # myCanvas”)。Width ($(window).width()) }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">

除非你想让画布自动提升你的图像数据(这就是James Black的答案,但它看起来不漂亮),你必须自己调整它的大小并重新绘制图像。画布居中

function resize() {

    var canvas = document.getElementById('game');
    var canvasRatio = canvas.height / canvas.width;
    var windowRatio = window.innerHeight / window.innerWidth;
    var width;
    var height;

    if (windowRatio < canvasRatio) {
        height = window.innerHeight;
        width = height / canvasRatio;
    } else {
        width = window.innerWidth;
        height = width * canvasRatio;
    }

    canvas.style.width = width + 'px';
    canvas.style.height = height + 'px';
};

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

2022的答案

在2022年,检查元素是否调整大小的推荐方法是使用ResizeObserver

const observer = new ResizeObserver(myResizeTheCanvasFn);
observer.observe(someCanvasElement);

它比窗户好。addEventListener('resize', myResizeTheCanvasFn)或onresize = myResizeTheCanvasFn,因为它处理画布调整大小的每一种情况,即使它与窗口调整大小无关。

同样,使用window也没有意义。innerWidth window.innerHeight。你想要画布本身的大小,而不是窗口的大小。这样,无论你把画布放在哪里,你都会得到正确的大小,而不必重写你的尺寸代码。

至于用画布填满窗户

html, body {
  height: 100%;
}
canvas {
  width: 100%;
  height: 100%;
  display: block;   /* this is IMPORTANT! */
}

你需要display: block的原因是因为默认情况下画布是内联的,这意味着它在结尾包含额外的空间。没有显示:块你将得到一个滚动条。许多人通过在文档正文中添加overflow: hidden来修复滚动条问题,但这只是隐藏了画布的CSS设置不正确的事实。最好是修复bug(将canvas设置为display: block而不是使用overflow: hidden隐藏bug)

完整的示例

const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); const observer = new ResizeObserver((entries) => { canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; }); observer.observe(canvas) // not import but draw something just to showcase const hsla = (h, s, l, a) => `hsla(${h * 360}, ${s * 100}%, ${l * 100}%, ${a})`; function render(time) { const {width, height} = canvas; ctx.clearRect(0, 0, width, height); ctx.save(); ctx.translate(width / 2, height / 2); ctx.rotate(time * 0.0001); const range = Math.max(width, height) * 0.8; const size = 64 + Math.sin(time * 0.001) * 50; for (let i = 0; i < range; i += size) { ctx.fillStyle = hsla(i / range * 0.3 + time * 0.0001, 1, 0.5, 1); ctx.fillRect( i, -range, size, range * 2); ctx.fillRect(-i, -range, size, range * 2); } ctx.restore(); requestAnimationFrame(render) } requestAnimationFrame(render) html, body { height: 100%; margin: 0; } canvas { width: 100%; height: 100%; display: block; } <canvas></canvas>

注意:还有其他与调整画布大小相关的问题。特别是如果你想处理不同的devicePixelRatio设置。请参阅本文了解更多信息。