상세 컨텐츠

본문 제목

html5 자바스크립트 canvas 풀스크린 스케일링 확대 관련

WEB/JavaScript

by AlrepondTech 2016. 6. 21. 02:08

본문

반응형
728x170

 

 

 

 

=================================

=================================

=================================

 

 

 

 

 

 

출처: http://www.html5rocks.com/en/tutorials/casestudies/gopherwoord-studios-resizing-html5-games/

Introduction

In the summer of 2010, we created Sand Trap, a game that we entered in a competition on HTML5 games for mobile phones. But most mobile phones either displayed only part of the game or made the game too small—making it completely unplayable. So we took it upon ourselves to make the game fluidly adjust to match any resolution. After a bit of re-programming and using ideas outlined in this article, we had a game that scaled across any modern browser, whether it ran in a desktop or a mobile device.

 

 

This approach worked well for Sand Trap, so we used the same method on our latest game, Thwack!!. The game automatically adjusts screen resolutions to fit both full-screen and custom-sized windows, as shown in the screenshots below.

Implementing this required taking advantage of both CSS and JavaScript. Using CSS to fill the whole screen is trivial, but CSS does not allow you to maintain the same width-to-height ratio to prevent stretching of the canvas and game area. That's where JavaScript comes in. You can rescale document elements with JavaScript and trigger the resize on window events.

Preparing the Page

The first step is to designate the area on the page where the game will take place. If you include this as a div block, you can place other tags or a canvas element within it. By setting it up correctly, these child elements will inherit the scaling of the parent div block.

If you have two parts to your game area, a play area and a score-keeping area, it might look like this:

<div id=”gameArea”>   <canvas id=”gameCanvas”></canvas>   <div id=”statsPanel”></div> </div>

Once you have a basic document structure, you can give these elements a few CSS properties to prepare them for resizing. Many of the CSS properties for “gameArea” are manipulated directly by JavaScript, but in order for them to work, set up a few other CSS properties starting with the parent gameArea div block:

#gameArea {   position: absolute;   left:     50%;   top:      50%; }

This puts the top left corner of the canvas in the center of the screen. The JavaScript auto-resize function described in the next section manipulates additional CSS properties to resize the game area and center it in the window.

Since the game area is automatically resized according to the dimensions of the window, you do not want the dimensions in pixels for the gameArea div block’s child elements; instead, you want it in percentages. Pixel values do not allow inner elements to scale with the parent div as it changes. However, it may be helpful to start with pixels and then convert them to percentages once you have a layout that you like.

For this example, start with the game area being 300 pixels tall and 400 pixels wide. The canvas covers the entire game area, and a semitransparent stats panel runs along the bottom at 24 pixels tall, as shown in Figure 1.

 

 

 


Figure 1: Dimensions of gameArea child elements in pixels

Translating these values to percentages makes the canvas 100% in width and 100% in height (of gameArea, not the window). Dividing 24 by 300 gives the height of the stats panel at 8%, and, since it will cover the bottom of the game area, it’s width will also be 100%, as seen in Figure 2.

 

 

 


Figure 2: Dimensions of gameArea child elements in percentages

Now that you have determined the dimensions of the game area and its child elements, you can put together the CSS properties for the two inside elements as follows:

#gameCanvas {   width: 100%;   height: 100%; }
#statsPanel {   position: absolute;   width: 100%;   height: 8%;   bottom: 0;   opacity: 0.8; }

Resizing the Game

Now you are ready to create a function to handle the window being resized. First, grab a reference to the parent gameArea document element.

var gameArea = document.getElementById('gameArea');

Since you are not concerned about the exact width or height, the next piece of information you need to set is the ratio of width to height. Using your earlier reference of a game area of 400 pixels wide and 300 pixels high, you know that you want to set the aspect ratio at 4 units wide and 3 units high.

var widthToHeight = 4 / 3;

Since this function is called whenever the window is resized, you also want to grab the window’s new dimensions so you are able to adjust your game’s dimensions to match. Find this by using the window’s innerWidth and innerHeight properties.

var newWidth = window.innerWidth; var newHeight = window.innerHeight;

Just as you determined the ratio of width to height you want, now you can determine the window’s current width to height ratio:

var newWidthToHeight = newWidth / newHeight;

This allows you to decide whether to make the game fill the screen vertically or horizontally, as shown in Figure 3.

 

 

 


Figure 3: Fitting the gameArea element to the window while maintaining aspect ratio

If the desired game area shape is wider than the window’s shape (and height is shorter), you need to fill up the window horizontally and leave margins along the top and bottom. Likewise, if the desired game area shape is higher than the window’s shape (and the width is narrower), you need to fill up the window vertically and leave margins along the left and right.

To do this, test your desired ratio of width to height with the current window’s ratio of width to height and make the appropriate adjustments as follows:

if (newWidthToHeight > widthToHeight) {   // window width is too wide relative to desired game width   newWidth = newHeight * widthToHeight;   gameArea.style.height = newHeight + 'px';   gameArea.style.width = newWidth + 'px'; } else { // window height is too high relative to desired game height   newHeight = newWidth / widthToHeight;   gameArea.style.width = newWidth + 'px';   gameArea.style.height = newHeight + 'px'; }

Now that you have adjusted the width and height of the game area, you need to center things up by placing a negative margin on the top that is half of the height and on the left that is half of the width. Remember that CSS is already placing the top-left corner of the gameArea div at the exact center of the window, so this centers the game area in the window:

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

You would also want to automatically adjust the font size. If you have all of the child elements using em, you can simply set the fontSize CSS property of the gameArea div block to a value determined by its size.

gameArea.style.fontSize = (newWidth / 400) + 'em';

Lastly, you want to make the canvas drawing dimensions match its new width and height. Note that the rest of the game code must keep game engine dimensions separate from the canvas drawing dimensions to accommodate for a dynamic canvas resolution.

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

So the completed resize function might look something like this:

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

Now, you want these adjustments to be made automatically whenever the window is resized or, in the case of mobile devices, the screen orientation is changed. Handle these events by having them call your resizeGame() function like so:

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

If the window is resized too high or the screen’s orientation is vertical, you are making width 100% of the window, and if the window is resized too wide or the screen’s orientation is horizontal, you are making height 100% of the window. The remaining dimension is sized according to the predetermined width-to-height aspect ratio.

Summary

Gopherwood Studios has used versions of this structure for all of our HTML5 games and it has proved very useful for accommodating multiple screen resolutions and various mobile devices. Additionally, with the aid of a full screen browser, this gives our web games an immersive experience more akin to traditional desktop gaming than many browser-based games. We look forward to more innovations in web games as HTML5 and web technologies continue to evolve.

 

 

 

 

=================================

=================================

=================================

 

 

 

출처: http://stackoverflow.com/questions/4288253/html5-canvas-100-width-height-of-viewport

 

I am trying to create a canvas element that takes up 100% of the width and height of the viewport.
You can see in my example here that is occurring, however it is adding scroll bars in both Chrome and FireFox. How can I prevent the extra scroll bars and just provide exactly the width and height of the window to be the size of the canvas?
shareimprove this question
 

6 Answers

up vote158down voteaccepted
In order to make the canvas full screen width and height always, meaning even when the browser is resized, you need to run your draw loop within a function that resizes the canvas to the window.innerHeight and window.innerWidth.
Example: http://jsfiddle.net/jaredwilli/qFuDr/

HTML

<canvas id="canvas"></canvas>

JavaScript

(function() { var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'); // resize the canvas to fill browser window dynamically window.addEventListener('resize', resizeCanvas, false); function resizeCanvas() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; /** * Your drawings need to be inside this function otherwise they will be reset when * you resize the browser window and the canvas goes will be cleared. */ drawStuff(); } resizeCanvas(); function drawStuff() { // do your drawing stuff here } })();

CSS

* { margin:0; padding:0; } /* to remove the top and left whitespace */ html, body { width:100%; height:100%; } /* just to be sure these are full screen*/ canvas { display:block; } /* To remove the scrollbars */
That is how you properly make the canvas full width and height of the browser. You just have to put all the code for drawing to the canvas in the drawStuff() function.
shareimprove this answer
 
    
Why is it necessary to remove the padding and set width, height to 100%? – Kos Jan 22 '13 at 17:07
1  
I believe it is mainly for overriding the user stylesheet which the browser has defaults for. If you are using some kind of normalize or reset css file, this isn't necessary since that will be taken care of already. – jaredwilli May 24 '13 at 15:16
    
If you expect quite a lot of resizing; on a portrait/landscape device for instance, you'd want to debounce the resize otherwise you'll flood the browser. – dooburt Apr 8 '14 at 8:07
7  
display: block: Not only does this remove scrollbars, but it removes 2px from the document body's height, that are normally added under text lines inside a block. So +1 for that – Neptilo Dec 18 '14 at 13:41
1  
Kudos for display: block trick! – SpyBot Apr 29 '15 at 5:42
You can try viewport units (CSS3):
canvas { height: 100vh; width: 100vw; display: block; }
shareimprove this answer
 
3  
Add display: block; and it does the job. – superlukas Aug 20 '14 at 12:40 
8  
I tried this and found that in Chrome and Firefox, the canvas simply shows the image stretched to the full viewport. Even newly drawn elements are stretched, as well. – Daniel Allen Langdon Aug 21 '14 at 3:03
1  
@Daniel is right - this answer is wrong. It won't set the internal dimension of the canvas context, but rather the dimensions of the DOM element. For the difference, see my answer to a related question. – Dan Dascalescu Jul 3 '15 at 2:32
    
This method does not work, it stretches the text. You unfortunately have to use JS. – i336_ May 10 at 1:56
I'll answer the more general question of how to have a canvas dynamically adapt in size upon window resize. The accepted answer appropriately handles the case where width and height are both supposed to be 100%, which is what was asked for, but which also will change the aspect ratio of the canvas. Many users will want the canvas to resize on window resize, but while keeping the aspect ratio untouched. It's not the exact question, but it "fits in", just putting the question into a slightly more general context.
The window will have some aspect ratio (width / height), and so will the canvas object. How you want these two aspect ratios to relate to each other is one thing you'll have to be clear about, there is no "one size fits all" answer to that question - I'll go through some common cases of what you might want.
Most important thing you have to be clear about: the html canvas object has a width attribute and a height attribute; and then, the css of the same object also has a width and a height attribute. Those two widths and heights are different, both are useful for different things.
Changing the width and height attributes is one method with which you can always change the size of your canvas, but then you'll have to repaint everything, which will take time and is not always necessary, because some amount of size change you can accomplish via the css attributes, in which case you do not redraw the canvas.
I see 4 cases of what you might want to happen on window resize (all starting with a full screen canvas)
1: you want the width to remain 100%, and you want the aspect ratio to stay as it was. In that case, you do not need to redraw the canvas; you don't even need a window resize handler. All you need is
$(ctx.canvas).css("width", "100%");
where ctx is your canvas context. fiddle: resizeByWidth
2: you want width and height to both stay 100%, and you want the resulting change in aspect ratio to have the effect of a stretched-out image. Now, you still don't need to redraw the canvas, but you need a window resize handler. In the handler, you do
$(ctx.canvas).css("height", window.innerHeight);
fiddle: messWithAspectratio
3: you want width and height to both stay 100%, but the answer to the change in aspect ratio is something different from stretching the image. Then you need to redraw, and do it the way that is outlined in the accepted answer.
fiddle: redraw
4: you want the width and height to be 100% on page load, but stay constant thereafter (no reaction to window resize.
fiddle: fixed
All fiddles have identical code, except for line 63 where the mode is set. You can also copy the fiddle code to run on your local machine, in which case you can select the mode via a querystring argument, as ?mode=redraw
shareimprove this answer
 
http://jsfiddle.net/mqFdk/10/
<!DOCTYPE html> <html> <head> <title>aj</title> </head> <body> <canvas id="c"></canvas> </body> </html>
with CSS
body { margin: 0; padding: 0 } #c { position: absolute; width: 100%; height: 100%; overflow: hidden }
shareimprove this answer
 
    
This works, but it leaves my canvas without a defined width and height. The canvas width and height must be defined on the element I believe. – aherrick Nov 26 '10 at 22:49
    
@aherrick: No, you do not have to have an explicit width/height set on the canvas element for it to work. This code should work fine. – Jon Adams Sep 13 '11 at 14:04
9  
Actually yes, canvas elements do need an explicit width/height set. Without it they default to some browser pre-set (in chrome, I think it's 300x150px) size. All drawing to the canvas gets interpreted at this size and then scaled to 100% of the viewport size. Try drawing anything in your canvas to see what I mean -- it'll be distorted. – zyklus Dec 13 '11 at 8:46
    
if you're trying to make the canvas 100% width and height then that doesnt even matter at all. you just resize it anyways – jaredwilli Jan 21 '12 at 12:58
1  
The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size. – jaredwilli Jan 21 '12 at 13:05
I was looking to find the answer to this question too, but the accepted answer was breaking for me. Apparently using window.innerWidth isn't portable. It does work in some browsers, but I noticed Firefox didn't like it.
Gregg Tavares posted a great resource here that addresses this issue directly:http://webglfundamentals.org/webgl/lessons/webgl-anti-patterns.html (See anti-pattern #'s 3 and 4).
Using canvas.clientWidth instead of window.innerWidth seems to work nicely.
Here's Gregg's suggested render loop:
function resize() { var width = gl.canvas.clientWidth; var height = gl.canvas.clientHeight; if (gl.canvas.width != width || gl.canvas.height != height) { gl.canvas.width = width; gl.canvas.height = height; return true; } return false; } var needToRender = true; // draw at least once function checkRender() { if (resize() || needToRender) { needToRender = false; drawStuff(); } requestAnimationFrame(checkRender); } checkRender();
shareimprove this answer
 
(Expanding upon 動靜能量's answer)
Style the canvas to fill the body. When rendering to the canvas take its size into account.
http://jsfiddle.net/mqFdk/356/
<!DOCTYPE html> <html> <head> <title>aj</title> </head> <body> <canvas id="c"></canvas> </body> </html>
CSS:
body { margin: 0; padding: 0 } #c { position: absolute; width: 100%; height: 100%; overflow: hidden }
Javascript:
function redraw() { var cc = c.getContext("2d"); c.width = c.clientWidth; c.height = c.clientHeight; cc.scale(c.width, c.height); // Draw a circle filling the canvas. cc.beginPath(); cc.arc(0.5, 0.5, .5, 0, 2*Math.PI); cc.fill(); } // update on any window size change. window.addEventListener("resize", redraw); // first draw redraw();
shareimprove this answer

 

 

 

=================================

=================================

=================================

 

 

 

 

출처: http://stackoverflow.com/questions/1664785/resize-html5-canvas-to-fit-window

 

 

How can I automatically scale the HTML5 <canvas> element to fit the page?
For example, I can get a <div> to scale by setting the height and width properties to 100%, but a <canvas> won't scale, will it?
shareimprove this question
 
1  
why canvas{width:100%;height:100%} don't work? – zloctb Dec 16 '14 at 17:59
9  
@zloctb - That will scale up the canvas directly, which stretches your image. – Derek 朕會功夫 Jan 2 '15 at 20:26

13 Answers

up vote251down voteaccepted
I believe I have found an elegant solution to this:
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: 0px; }
Hasn't had any large negative performance impact for me, so far.
shareimprove this answer
 
3  
You probably have to disable margin with body, html { margin: 0px;} – Nicklas A. Sep 11 '11 at 3:43
33  
Is this preferable to listening to the resize event? – Eric Sep 28 '11 at 7:15
2  
@dan: some FF add-ons can botch the innerWidth property. – jerseyboy Jan 25 '12 at 14:37
12  
@Elisabeth: To get rid of the scrollbars, add "overflow: hidden" to the style of the html and body elements. See thefutureoftheweb.com/blog/100-percent-height-interface – denisw Mar 16 '12 at 7:45
13  
I did this plus I also set canvas to display: block (it seemed to be defaulting to display: inline which was creating extra space!). – Elisabeth Apr 5 '12 at 22:00
Basically what you have to do is to bind the onresize event to your body, once you catch the event you just need to resize the canvas using window.innerWidth and 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>
shareimprove this answer
 
1  
You could just use an event listener. – David Corbin Feb 28 '14 at 21:47
    
This has margins and shows scrollbars, plus you have to resize the screen before it does anything. – ArtOfWarfare May 28 at 18:16
    
What if the canvas is larger than the viewport (when making the viewport narrower or shorter)? This solution does not seem to handle that. – LayZee Jun 6 at 5:31
    
@ArtOfWarfare original questions don't mention anything about styles. But you can stylize it with css and remove margins and hide scroll bars if you like. And you simply can add ` <body onload="resize_canvas()">` then when page load then resize canvas. – equiman Jun 6 at 5:56
    
@LayZee original question saya bout scale the canvas to fit the page, not a viewport. That's can be another question. – equiman Jun 6 at 6:03
Setting the canvas coordinate space width and height based on the browser client's dimensions requires you to resize and redraw whenever the browser is resized.
A less convoluted solution is to maintain the drawable dimensions in Javascript variables, but set the canvas dimensions based on the screen.width, screen.height dimensions. Use CSS to fit:
#containingDiv { overflow: hidden; } #myCanvas { position: absolute; top: 0px; left: 0px; }
The browser window generally won't ever be larger than the screen itself (except where the screen resolution is misreported, as it could be with non-matching dual monitors), so the background won't show and pixel proportions won't vary. The canvas pixels will be directly proportional to the screen resolution unless you use CSS to scale the canvas.
shareimprove this answer
 
6  
Rescaling canvas with CSS is troublesome. At least on Chrome and Safari, mouse/touch event positions will not correspond 1:1 with canvas pixel positions, and you'll have to transform the coordinate systems. – jerseyboy Dec 1 '11 at 15:44
The following solution worked for me the best. Since I'm relatively new to coding, I like to have visual confirmation that something is working the way I expect it to. I found it at the following site:http://htmlcheats.com/html/resize-the-html5-canvas-dyamically/
Here's the code:
<!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>
The blue border shows you the edge of the resizing canvas, and is always along the edge of the window, visible on all 4 sides, which was NOT the case for some of the other above answers. Hope it helps.
shareimprove this answer
 
Unless you want the canvas to upscale your image data automatically (that's what James Black's answer talks about, but it won't look pretty), you have to resize it yourself and redraw the image.http://stackoverflow.com/questions/1152203/centering-a-canvas/1646370#1646370
shareimprove this answer
 
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);
shareimprove this answer
 
    
Nice, when the ratio is important – sarkiroka Mar 18 at 10:46
pure CSS approach adding to solution of @jerseyboy above.
Works in Firefox (tested in v29), Chrome (tested in v34) and Internet Explorer (tested in v11).

<!DOCTYPE html> <html> <head> <style> html, body { width: 100%; height: 100%; margin: 0; } canvas { background: #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>
Link to the example: http://temporaer.net/open/so/140502_canvas-fit-to-window.html
But take care, as @jerseyboy states in his comment:
Rescaling canvas with CSS is troublesome. At least on Chrome and Safari, mouse/touch event positions will not correspond 1:1 with canvas pixel positions, and you'll have to transform the coordinate systems.
shareimprove this answer
 
    
CSS way stretches the canvas, thus rendered images get stretched. This is not good compared to resizing the canvas. With little adjustment, Craig's answer works best. – Nayan Apr 6 '15 at 4:21
If your div completely filled the webpage then you can fill up that div and so have a canvas that fills up the div.
You may find this interesting, as you may need to use a css to use percentage, but, it depends on which browser you are using, and how much it is in agreement with the spec:http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element
The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.
You may need to get the offsetWidth and height of the div, or get the window height/width and set that as the pixel value.
shareimprove this answer
 
(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(); }); }());
shareimprove this answer
 
If you're interested in preserving aspect ratios and doing so in pure CSS (given the aspect ratio) you can do something like below. The key is the padding-bottom on the ::content element that sizes the container element. This is sized relative to its parent's width, which is 100% by default. The ratio specified here has to match up with the ratio of the sizes on the canvas element.


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);
.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%; }
<div class=container> <div class=wrapper> <canvas width=1200 height=600></canvas> </div> </div>

shareimprove this answer
 
I think this is what should we exactly do: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);
shareimprove this answer
 
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(); });
shareimprove this answer
 
I'm using sketch.js so after I run the init command for the canvas i change the width and height with jquery. It bases the dimensions on the parent element.
$('#DrawCanvas').sketch().attr('height',$('#DrawCanvas').parent().height()).attr('width',$('#DrawCanvas').parent().width());
shareimprove this answer

 

=================================

=================================

=================================

 

 

출처: http://stackoverflow.com/questions/4037212/html-canvas-full-screen

 

I'm playing with the following application using the HTML Canvas: http://driz.co.uk/particles/
At the moment it is set to 640x480 pixels, but I would like to make it full screen as it will be shown a projector. However as far as I can tell I cannot set the canvas size to be 100% as the variables only except numbers and not the %. Using CSS just stretches it rather than making it actual full screen.
Any ideas?
EDIT: Tried finding the height and width using jQuery but it breaks the canvas any ideas why?
var $j = jQuery.noConflict(); var canvas; var ctx; var canvasDiv; var outerDiv; var canvasW = $j('body').width(); var canvasH = $j('body').height(); //var canvasW = 640; //var canvasH = 480; var numMovers = 550; var movers = []; var friction = .96; var radCirc = Math.PI * 2; var mouseX, mouseY, mouseVX, mouseVY, prevMouseX = 0, prevMouseY = 0; var isMouseDown = true; function init() { canvas = document.getElementById("mainCanvas"); if( canvas.getContext ) { setup(); setInterval( run , 33 ); } } function setup() { outerDiv = document.getElementById("outer"); canvasDiv = document.getElementById("canvasContainer"); ctx = canvas.getContext("2d"); var i = numMovers; while( i-- ) { var m = new Mover(); m.x = canvasW * .5; m.y = canvasH * .5; m.vX = Math.cos(i) * Math.random() * 25; m.vY = Math.sin(i) * Math.random() * 25; m.size = 2; movers[i] = m; } document.onmousedown = onDocMouseDown; document.onmouseup = onDocMouseUp; document.onmousemove = onDocMouseMove; } function run() { ctx.globalCompositeOperation = "source-over"; ctx.fillStyle = "rgba(8,8,12,.65)"; ctx.fillRect( 0 , 0 , canvasW , canvasH ); ctx.globalCompositeOperation = "lighter"; mouseVX = mouseX - prevMouseX; mouseVY = mouseY - prevMouseY; prevMouseX = mouseX; prevMouseY = mouseY; var toDist = canvasW / 1.15; var stirDist = canvasW / 8; var blowDist = canvasW / 2; var Mrnd = Math.random; var Mabs = Math.abs; var Msqrt = Math.sqrt; var Mcos = Math.cos; var Msin = Math.sin; var Matan2 = Math.atan2; var Mmax = Math.max; var Mmin = Math.min; var i = numMovers; while( i-- ) { var m = movers[i]; var x = m.x; var y = m.y; var vX = m.vX; var vY = m.vY; var dX = x - mouseX; var dY = y - mouseY; var d = Msqrt( dX * dX + dY * dY ); var a = Matan2( dY , dX ); var cosA = Mcos( a ); var sinA = Msin( a ); if( isMouseDown ) { if( d < blowDist ) { var blowAcc = ( 1 - ( d / blowDist ) ) * 2; vX += cosA * blowAcc + .5 - Mrnd(); vY += sinA * blowAcc + .5 - Mrnd(); } } if( d < toDist ) { var toAcc = ( 1 - ( d / toDist ) ) * canvasW * .0014; vX -= cosA * toAcc; vY -= sinA * toAcc; } if( d < stirDist ) { var mAcc = ( 1 - ( d / stirDist ) ) * canvasW * .00022; vX += mouseVX * mAcc; vY += mouseVY * mAcc; } vX *= friction; vY *= friction; var avgVX = Mabs( vX ); var avgVY = Mabs( vY ); var avgV = ( avgVX + avgVY ) * .5; if( avgVX < .1 ) vX *= Mrnd() * 3; if( avgVY < .1 ) vY *= Mrnd() * 3; var sc = avgV * .45; sc = Mmax( Mmin( sc , 3.5 ) , .4 ); var nextX = x + vX; var nextY = y + vY; if( nextX > canvasW ) { nextX = canvasW; vX *= -1; } else if( nextX < 0 ) { nextX = 0; vX *= -1; } if( nextY > canvasH ) { nextY = canvasH; vY *= -1; } else if( nextY < 0 ) { nextY = 0; vY *= -1; } m.vX = vX; m.vY = vY; m.x = nextX; m.y = nextY; ctx.fillStyle = m.color; ctx.beginPath(); ctx.arc( nextX , nextY , sc , 0 , radCirc , true ); ctx.closePath(); ctx.fill(); } //rect( ctx , mouseX - 3 , mouseY - 3 , 6 , 6 ); } function onDocMouseMove( e ) { var ev = e ? e : window.event; mouseX = ev.clientX - outerDiv.offsetLeft - canvasDiv.offsetLeft; mouseY = ev.clientY - outerDiv.offsetTop - canvasDiv.offsetTop; } function onDocMouseDown( e ) { isMouseDown = true; return false; } function onDocMouseUp( e ) { isMouseDown = true; return false; } // ========================================================================================== function Mover() { this.color = "rgb(" + Math.floor( Math.random()*255 ) + "," + Math.floor( Math.random()*255 ) + "," + Math.floor( Math.random()*255 ) + ")"; this.y = 0; this.x = 0; this.vX = 0; this.vY = 0; this.size = 0; } // ========================================================================================== function rect( context , x , y , w , h ) { context.beginPath(); context.rect( x , y , w , h ); context.closePath(); context.fill(); } // ==========================================================================================
shareimprove this question
 
    
Check my edits in response to your edits. – Nick Larsen Oct 27 '10 at 21:47
    
What's the HTML for this document? – bafromca May 4 '12 at 15:40

10 Answers

The javascript has
var canvasW = 640; var canvasH = 480;
in it. Try changing those as well as the css for the canvas.
Or better yet, have the initialize function determine the size of the canvas from the css!
in response to your edits, change your init function:
function init() { canvas = document.getElementById("mainCanvas"); canvas.width = document.body.clientWidth; //document.width is obsolete canvas.height = document.body.clientHeight; //document.height is obsolete canvasW = canvas.width; canvasH = canvas.height; if( canvas.getContext ) { setup(); setInterval( run , 33 ); } }
Also remove all the css from the wrappers, that just junks stuff up. You have to edit the js to get rid of them completely though... I was able to get it full screen though.
html, body { overflow: hidden; }
Editdocument.width and document.height are obsolete. Replace with document.body.clientWidth and document.body.clientHeight
shareimprove this answer
 
The newest Chrome and Firefox support a fullscreen API, but setting to fullscreen is like a window resize. Listen to the onresize-Event of the window-object:
$(window).bind("resize", function(){ var w = $(window).width(); var h = $(window).height(); $("#mycanvas").css("width", w + "px"); $("#mycanvas").css("height", h + "px"); }); //using HTML5 for fullscreen (only newest Chrome + FF) $("#mycanvas")[0].webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); //Chrome $("#mycanvas")[0].mozRequestFullScreen(); //Firefox //... //now i want to cancel fullscreen document.webkitCancelFullScreen(); //Chrome document.mozCancelFullScreen(); //Firefox
This doesn't work in every browser. You should check if the functions exist or it will throw an js-error.
for more info on html5-fullscreen check this: http://updates.html5rocks.com/2011/10/Let-Your-Content-Do-the-Talking-Fullscreen-API
shareimprove this answer
 
You can just insert the following in to your main html page, or a function:
canvas.width = window.innerWidth; canvas.height = window.innerHeight;
That should do the job
shareimprove this answer
 
    
Works great! simple as well! – KuKu Jul 22 '14 at 16:04
All you need to do is set the width and height attributes to be the size of the canvas, dynamically. So you use CSS to make it stretch over the entire browser window, then you have a little function in javascript which measures the width and height, and assigns them. I'm not terribly familliar with jQuery, so consider this psuedocode:
window.onload = window.onresize = function() { theCanvas.width = theCanvas.offsetWidth; theCanvas.height = theCanvas.offsetHeight; }
The width and height attributes of the element determine how many pixels it uses in it's internal rendering buffer. Changing those to new numbers causes the canvas to reinitialise with a differently sized, blank buffer. Browser will only stretch the graphics if the width and height attributes disagree with the actual real world pixel width and height.
shareimprove this answer
 
    
If you're looking for actual full screen view for a projector, there are capable tools. Opera is a web browser with full screen support for example, so you can just manually switch it to full screen for your presentation. – Blixxy Oct 27 '10 at 23:53
On document load set the
canvas.width = window.innerWidth; canvas.height = window.innerHeight;
shareimprove this answer
 
it's simple, set canvas width and height to screen.width and screen.height. then press F11! think F11 should make full screen in most browsers does in FFox and IE.
shareimprove this answer
 
AFAIK, HTML5 does not provide an API which supports full screen.
This question has some view points on making html5 video full screen for example using webkitEnterFullscreen in webkit.
Is there a way to make html5 video fullscreen
shareimprove this answer
 
    
Any ideas on how I could get around this? – Cameron Oct 27 '10 at 20:11
You could just capture window resize events and set the size of your canvas to be the browser's viewport.
shareimprove this answer
 
    
trying that now using jquery but seems to break the code... any ideas? added code to my original question. – Cameron Oct 27 '10 at 21:16
Get the full width and height of the screen and create a new window set to the appropriate width and height, and with everything disabled. Create a canvas inside of that new window, setting the width and height of the canvas to the width - 10px and the height - 20px (to allow for the bar and the edges of the window). Then work your magic on that canvas.
shareimprove this answer
 
    
Tried doing that using jQuery look at my edited question – Cameron Oct 27 '10 at 21:00
function resize() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; render(); } window.addEventListener('resize', resize, false); resize(); function render() { // draw to screen here }
https://jsfiddle.net/jy8k6hfd/2/
 

 

 

=================================

=================================

=================================

 

 

출처: https://forums.adobe.com/thread/1819634

Hi,

 

I have an animation created in an HTML5 Canvas document. When viewed in the browser it is displayed at the document size, which is not suprising, but what I want to do is display it at full window size, scaled to fit. Basically I'm looking for the equivalent to AS3 scaleMode and align with the SWF set to 100% width and height. The publish settings don't have any options related to scaling, so I'm not sure where to look. How should I do this?

 

Thanks!

 

-Aaron


정확한 답변작성자: kglad 날짜: 2015. 4. 17 오전 9:53

except for the resizing which requires a resize listener, you can use:

 

<style>

#canvas{

    width: 100%;

    height: 100%;

}

</style>

 

 

=================================

=================================

=================================

 

 

 

 

반응형
그리드형


관련글 더보기

댓글 영역