[javascript] 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();
}


// ==========================================================================================

This question is related to javascript html canvas

The answer is


Because it was not posted yet and is a simple css fix:

#canvas {
    position:fixed;
    left:0;
    top:0;
    width:100%;
    height:100%;
}

Works great if you want to apply a fullscreen canvas background (for example with Granim.js).


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.


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/


You could just capture window resize events and set the size of your canvas to be the browser's viewport.


On document load set the

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

A - How To Calculate Full Screen Width & Height

Here is the functions;

canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

Check this out

B - How To Make Full Screen Stable With Resize

Here is the resize method for the resize event;

function resizeCanvas() {
    canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

    WIDTH = canvas.width;
    HEIGHT = canvas.height;

    clearScreen();
}

C - How To Get Rid Of Scroll Bars

Simply;

<style>
    html, body {
        overflow: hidden;
    }
</style>

D - Demo Code

_x000D_
_x000D_
<html>_x000D_
 <head>_x000D_
  <title>Full Screen Canvas Example</title>_x000D_
  <style>_x000D_
   html, body {_x000D_
    overflow: hidden;_x000D_
   }_x000D_
  </style>_x000D_
 </head>_x000D_
 <body onresize="resizeCanvas()">_x000D_
  <canvas id="mainCanvas">_x000D_
  </canvas>_x000D_
  <script>_x000D_
   (function () {_x000D_
    canvas = document.getElementById('mainCanvas');_x000D_
    ctx = canvas.getContext("2d");_x000D_
    _x000D_
    canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;_x000D_
    canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;_x000D_
    WIDTH = canvas.width;_x000D_
    HEIGHT = canvas.height;_x000D_
    _x000D_
    clearScreen();_x000D_
   })();_x000D_
   _x000D_
   function resizeCanvas() {_x000D_
    canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;_x000D_
    canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;_x000D_
    _x000D_
    WIDTH = canvas.width;_x000D_
    HEIGHT = canvas.height;_x000D_
    _x000D_
    clearScreen();_x000D_
   }_x000D_
   _x000D_
   function clearScreen() {_x000D_
    var grd = ctx.createLinearGradient(0,0,0,180);_x000D_
    grd.addColorStop(0,"#6666ff");_x000D_
    grd.addColorStop(1,"#aaaacc");_x000D_
_x000D_
    ctx.fillStyle = grd;_x000D_
    ctx.fillRect(  0, 0, WIDTH, HEIGHT );_x000D_
   }_x000D_
  </script>_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


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


If you want to show it in a presentation then consider using requestFullscreen() method

let canvas = document.getElementById("canvas_id");
canvas.requestFullscreen();

that should make it fullscreen whatever the current circumstances are.

also check the support table https://caniuse.com/?search=requestFullscreen


Well, I was looking to make my canvas fullscreen too, This is how i did it. I'll post the entire index.html since I am not a CSS expert yet : (basically just using position:fixed and width and height as 100% and top and left as 0% and i nested this CSS code for every tag. I also have min-height and min-width as 100%. When I tried it with a 1px border the border size was changing as I zoomed in and out but the canvas remained fullscreen.)

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
<head>_x000D_
<title>MOUSEOVER</title>_x000D_
<script "text/javascript" src="main.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body id="BODY_CONTAINER" style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
_x000D_
_x000D_
_x000D_
<div id="DIV_GUI_CONTAINER" style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
_x000D_
<canvas id="myCanvas"  style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
_x000D_
</canvas>_x000D_
_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

EDIT: add this to the canvas element:

_x000D_
_x000D_
<canvas id="myCanvas" width="" height="" style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
_x000D_
</canvas>
_x000D_
_x000D_
_x000D_

add this to the javascript

canvas.width = window.screen.width;

canvas.height = window.screen.height;

I found this made the drawing a lot smoother than my original comment.

Thanks.


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.


You can just insert the following in to your main html page, or a function:

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

Then to remove the margins on the page

html, body {
    margin: 0 !important;
    padding: 0 !important;
}

That should do the job


I hope it will be useful.

// Get the canvas element
var canvas = document.getElementById('canvas');

var isInFullScreen = (document.fullscreenElement && document.fullscreenElement !== null) ||
    (document.webkitFullscreenElement && document.webkitFullscreenElement !== null) ||
    (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
    (document.msFullscreenElement && document.msFullscreenElement !== null);

// Enter fullscreen
function fullscreen(){
    if(canvas.RequestFullScreen){
        canvas.RequestFullScreen();
    }else if(canvas.webkitRequestFullScreen){
        canvas.webkitRequestFullScreen();
    }else if(canvas.mozRequestFullScreen){
        canvas.mozRequestFullScreen();
    }else if(canvas.msRequestFullscreen){
        canvas.msRequestFullscreen();
    }else{
        alert("This browser doesn't supporter fullscreen");
    }
}

// Exit fullscreen
function exitfullscreen(){
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
    }else{
        alert("Exit fullscreen doesn't work");
    }
}

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


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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to canvas

How to make canvas responsive How to fill the whole canvas with specific color? Use HTML5 to resize an image before upload Convert canvas to PDF Scaling an image to fit on canvas Split string in JavaScript and detect line break Get distance between two points in canvas canvas.toDataURL() SecurityError Converting Chart.js canvas chart to image using .toDataUrl() results in blank image Chart.js canvas resize