天天看點

html設定視窗最小大小,調整HTML 5畫布的大小以适應視窗

下面的解決方案對我來說是最好的。因為我對編碼還比較陌生,是以我喜歡用視覺來确認某些東西正在以我預期的方式工作。我在以下地點找到了它:http:/htmlcheats.com/html/resize-the-html 5-畫布-dyamally/

下面是代碼:html>

Resize HTML5 canvas dynamically | www.htmlcheats.com

html, body {

width: 100%;

height: 100%;

margin: 0px;

border: 0;

overflow: hidden; 

display: block;  

}

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

}

})();