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:
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:
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:
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:
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.
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:
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:
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.
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?
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
<canvasid="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.
Why is it necessary to remove the padding and set width, height to 100%? – KosJan 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. – jaredwilliMay 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. – dooburtApr 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 – NeptiloDec 18 '14 at 13:41
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 LangdonAug 21 '14 at 3:03
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
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. – aherrickNov 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 AdamsSep 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. – zyklusDec 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 – jaredwilliJan 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. – jaredwilliJan 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() { varwidth = gl.canvas.clientWidth; varheight = gl.canvas.clientHeight; if (gl.canvas.width != width || gl.canvas.height != height) { gl.canvas.width = width; gl.canvas.height = height; returntrue; } returnfalse; } var needToRender = true; // drawat least once function checkRender() { if (resize() || needToRender) { needToRender = false; drawStuff(); } requestAnimationFrame(checkRender); } checkRender();
(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><canvasid="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); // firstdrawredraw();
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?
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. */functiondraw() { 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.
I did this plus I also set canvas to display: block (it seemed to be defaulting to display: inline which was creating extra space!). – ElisabethApr 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"><htmlxmlns="http://www.w3.org/1999/xhtml"><head><title>Canvas Resize</title><scripttype="text/javascript">functionresize_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><bodyonresize="resize_canvas()"><canvasid="canvas">Your browser doesn't support canvas</canvas></body></html>
This has margins and shows scrollbars, plus you have to resize the screen before it does anything. – ArtOfWarfareMay 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. – LayZeeJun 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. – equimanJun 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. – equimanJun 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.
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. – jerseyboyDec 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><metacharset="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><canvasid='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.
A 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><canvasid="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.
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. – NayanApr 6 '15 at 4:21
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.
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: 0050%; } .wrapper { position: absolute; top: 0; right: 0; left: 0; bottom: 0; } canvas { width: 100%; height: 100%; } <divclass=container><divclass=wrapper><canvaswidth=1200height=600></canvas></div></div>
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.
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; } elseif( nextX < 0 ) { nextX = 0; vX *= -1; } if( nextY > canvasH ) { nextY = canvasH; vY *= -1; } elseif( 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(); } // ==========================================================================================
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.widthis obsolete canvas.height = document.body.clientHeight; //document.heightis 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; } Edit: document.width and document.heightare obsolete. Replace with document.body.clientWidth and document.body.clientHeight
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
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
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.
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. – BlixxyOct 27 '10 at 23:53
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.
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
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.
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?
What should I edit in the HTML file? The <canvas> element doesn't seem to like percent widths. I've added a resize handler to set the canvas width/height to window.innerWidth and innerHeight, but the actual canvas drawings are not scaled.
I looked at the CreateJS Stage documentation and it doesn't seem to have a scaleMode or align property like AS3 Stage. It does have scaleX and scaleY... I guess I need to manually figure out what the scaleX and scaleY are?
BTW, at what point is your brain going to be full?? You've been answering my questions literally since I started using Flash MX about 10 years ago! Cheers.
I'm using the solution you worked out here and it works wonderfully. But I can't seem to get the height fixed correctly. Scroll bars appear to show the remaining content and I'd like it to be fixed just like the width is. Any ideas?
YES! That works. Thank you. (Hopefully) last question. When I place that overflow:hidden command in the css, it cuts off some of the content on the lower half of the stage/canvas. Does that have to do with the original size of the stage in Animate CC or is there something else I need to do to get that content to fix to the lower half of the stage as I placed it in Animate CC?
the css in message 4 specifies that the canvas is displayed and nothing below that. if you want some other div to be displayed, reference it instead of #canvas.
If I do want the text to scale, how do I do it but preserve the resolution? a good example of precisely what I'm trying to accomplish would be a site like: www.jasonbournemovie.com
I know you stated that it should show only that which is in the canvas. But for some reason, while the width is fixed just fine, the height of the animate cc html5 canvas requires scrolling to see the entirety of. I'm not understanding what I'm missing. Any ideas?
debounce
the resize otherwise you'll flood the browser. – dooburt Apr 8 '14 at 8:07display: 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:41display: block
trick! – SpyBot Apr 29 '15 at 5:42