=================================
=================================
=================================
출처: 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.
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.
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.
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? |
||
add a comment
|
158
|
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. |
||
22
|
|
||||||||||||||||
|
9
|
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 |
||
4
|
http://jsfiddle.net/mqFdk/10/
<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 } |
||||||||||||||||||||
|
2
|
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(); |
||
1
|
(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/ <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(); |
=================================
=================================
=================================
출처: 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? |
|||||||||
|
251
|
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. |
||||||||||||||||||||
|
16
|
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.
<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> |
||||||||||||||||||||
|
15
|
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. |
||||
|
10
|
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: <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. |
||
8
|
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
|
||
5
|
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);
|
||||
|
4
|
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). <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. |
||||
|
2
|
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. |
||
1
|
(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(); }); }());
|
||
0
|
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> |
|||
-1
|
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); |
||
-1
|
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(); }); |
||
-2
|
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()); |
=================================
=================================
=================================
출처: 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(); } // ========================================================================================== |
|||||||||
|
25
|
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; } Edit: document.width and document.height are obsolete. Replace with document.body.clientWidth and document.body.clientHeight |
|||
12
|
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 |
||
7
|
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 |
||||
|
3
|
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. |
||||
|
3
|
On document load set the
canvas.width = window.innerWidth; canvas.height = window.innerHeight; |
|||
1
|
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.
|
||
0
|
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 |
||||
|
0
|
You could just capture window resize events and set the size of your canvas to be the browser's viewport.
|
||||
|
0
|
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.
|
||||
|
0
|
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
=================================
=================================
=================================
'WEB > JavaScript' 카테고리의 다른 글
[JavaScript] 자바스크립트 Map 관련 (0) | 2017.11.07 |
---|---|
[JavaScript] 웹워커 Web Worker 웹에서 멀티 스레드 구현하기 (0) | 2017.11.06 |
자바스크립트 객체화 캡슐 private public 모음 관련 (0) | 2016.06.21 |
자바스크립트의 encodeURI 관련 (2) | 2016.06.03 |
[jsp] javascript encodeURI() 한글 인코딩 시 jsp URLDecoder에서 한글 깨짐현상 (0) | 2016.06.03 |
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