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

例如,我可以通过设置<div>height属性至100%得到width比例,但<canvas>不会比例,将它

有帮助吗?

解决方案

我相信我已经发现一个优雅的解决这样的:

<强>的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;
}

一直没有给我任何大的负面的性能影响,到目前为止。

其他提示

以下解决方案为我最好的。因为我是比较新的编码,我喜欢有视觉确认的东西是工作,我希望它的方式。我发现它在以下站点: http://htmlcheats.com/html/resize-the-html5-canvas- dyamically /

下面的代码:

<!DOCTYPE html>

<head>
    <meta charset="utf-8">
    <title>Resize HTML5 canvas dynamically | www.htmlcheats.com</title>
    <style>
    html, body {
      width: 100%;
      height: 100%;
      margin: 0px;
      border: 0;
      overflow: hidden; /*  Disable scrollbars */
      display: block;  /* No floating content on sides */
    }
    </style>
</head>

<body>
    <canvas id='c' style='position:absolute; left:0px; top:0px;'>
    </canvas>

    <script>
    (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();
        }
    })();

    </script>
</body> 
</html>

蓝色边框显示你调整大小画布边缘,并始终沿着窗口中,所有4个方面可见,这是因为某些其他上述答案的情况下的边缘。希望它帮助。

基本上你所要做的是将在onResize事件绑定到你的身体,一旦你抓住事件中,你只需要调整使用window.innerWidth和window.innerHeight在画布上。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Canvas Resize</title>

    <script type="text/javascript">
        function resize_canvas(){
            canvas = document.getElementById("canvas");
            if (canvas.width  < window.innerWidth)
            {
                canvas.width  = window.innerWidth;
            }

            if (canvas.height < window.innerHeight)
            {
                canvas.height = window.innerHeight;
            }
        }
    </script>
</head>

<body onresize="resize_canvas()">
        <canvas id="canvas">Your browser doesn't support canvas</canvas>
</body>
</html>

设置画布坐标基于所述浏览器客户机的空间的尺寸的宽度和高度需要你调整大小和重新绘制每当浏览器的尺寸调整。

一个较少复杂的解决方案是要保持在Javascript变量绘制的尺寸,而是基于screen.width,screen.height尺寸设置画布尺寸。使用CSS来适应:

#containingDiv { 
  overflow: hidden;
}
#myCanvas {
  position: absolute; 
  top: 0px;
  left: 0px;
} 

在浏览器视窗通常永远不会比屏幕本身的情况下(除非屏幕分辨率误报的,因为它可以是具有非匹配的双显示器),所以背景将不会显示与像素的比例获得了”吨变化。除非你使用CSS来缩放画布画布像素将是成正比的屏幕分辨率。

一个的纯CSS 方法加入@jerseyboy的溶液上方。结果 在Firefox(在V29测试),铬(在V34测试)和Internet Explorer(在V11测试)。

<!DOCTYPE html>
<html>
    <head>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            margin: 0;
        }
        canvas {
            background-color: #ccc;
            display: block;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="500" height="500"></canvas>
    <script>
        var canvas = document.getElementById('canvas');
        if (canvas.getContext) {
            var ctx = canvas.getContext('2d');
            ctx.fillRect(25,25,100,100);
            ctx.clearRect(45,45,60,60);
            ctx.strokeRect(50,50,50,50);
        }
    </script>
</body>
</html>

链接到例如: http://temporaer.net/open /so/140502_canvas-fit-to-window.html

不过要小心,因为在他的评论@jerseyboy状态:

  

重新缩放画布与CSS是麻烦的。至少在Chrome和   Safari浏览器,鼠标/触摸事件的位置将不对应1:1与   帆布像素位置,你就必须转换坐标   系统

除非你想在画布高档自动将图像数据(这就是詹姆斯·布莱克的有关应答会谈,但它不会看起来很漂亮),你必须自己去调整它,并重新绘制图像。 居中帆布

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);

如果您的DIV完全充满的网页,那么你可以填补该div等具有填补了DIV的画布。

您可能会发现这个有趣的,因为你可能需要使用一个CSS使用百分比,但是,这取决于您使用的浏览器,以及有多少是符合规范的协议: HTTP: //www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element

  

画布的固有尺寸   元件等于的大小   坐标空间,与数字   解释在CSS像素。然而,   该元件可以任意地被定尺寸   由样式表。在渲染过程中,   图像被缩放以适合此布局   大小

您可能需要获得的div offsetWidth和高度,或获取窗口高度/宽度,并设置作为像素值。

<强> CSS

body { margin: 0; } 
canvas { display: block; } 

<强>的JavaScript

window.addEventListener("load", function()
{
    var canvas = document.createElement('canvas'); document.body.appendChild(canvas);
    var context = canvas.getContext('2d');

    function draw()
    {
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.beginPath();
        context.moveTo(0, 0); context.lineTo(canvas.width, canvas.height); 
        context.moveTo(canvas.width, 0); context.lineTo(0, canvas.height); 
        context.stroke();
    }
    function resize()
    {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        draw();
    }
    window.addEventListener("resize", resize);
    resize();
});

如果您有兴趣保持纵横比和纯CSS这样做(给定的宽高比),你可以这样做以下。最关键的是尺寸的padding-bottom元素::content元素的container。这是相对于其父的宽度,这是默认100%大小。此处指定的比率必须与canvas元件上的大小的比率匹配。

// Javascript

var canvas = document.querySelector('canvas'),
    context = canvas.getContext('2d');

context.fillStyle = '#ff0000';
context.fillRect(500, 200, 200, 200);

context.fillStyle = '#000000';
context.font = '30px serif';
context.fillText('This is some text that should not be distorted, just scaled', 10, 40);
/*CSS*/

.container {
  position: relative; 
  background-color: green;
}

.container::after {
  content: ' ';
  display: block;
  padding: 0 0 50%;
}

.wrapper {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
}

canvas {
  width: 100%;
  height: 100%;
}
<!-- HTML -->

<div class=container>
  <div class=wrapper>
    <canvas width=1200 height=600></canvas>  
  </div>
</div>

(function() {

    // get viewport size
    getViewportSize = function() {
        return {
            height: window.innerHeight,
            width:  window.innerWidth
        };
    };

    // update canvas size
    updateSizes = function() {
        var viewportSize = getViewportSize();
        $('#myCanvas').width(viewportSize.width).height(viewportSize.height);
        $('#myCanvas').attr('width', viewportSize.width).attr('height', viewportSize.height);
    };

    // run on load
    updateSizes();

    // handle window resizing
    $(window).on('resize', function() {
        updateSizes();
    });

}());

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

类似的东西

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

我觉得这是我们应该做的正是:的 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);

首先,你不能使用width和height属性可以改变其大小(用我的方式,至少),因为这将打破它。你可以这样做: HTML:

<canvas id = 'myCanvas'></canvas>

JS:

var canvas = document.getElementById('myCanvas');

var W = window.innerWidth;
var H = window.innerHeight;
canvas.width = W;
canvas.height = H;
canvas.style.position = 'absolute';
//Or set the position to absolute using CSS

(请原谅我的拼写错误,我倾向于做了很多)

我使用sketch.js所以后我运行画布我改变宽度和高度与jquery init命令。它的碱基父元素的尺寸。

  

$( '#DrawCanvas')。素描()。ATTR( '高度',$( '#DrawCanvas')。亲本()。高度())。ATTR( '宽度',$( '#DrawCanvas' 。).parent()宽度());

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top