简体   繁体   中英

How can I fullscreen my canvas & make it fill the screen?

I have a HTML5 canvas that when it goes into fullscreen, it does not fill the entire screen.

If I change only the canvas.style.width/height then it works but the display looks bad and also the mouse coordinates are misplaced.

js

var canvas = document.getElementById("canvas");

var mouseX = 0;
var mouseY = 0;

canvas.style.left = 0;
canvas.style.top = 0;

onmousemove = function(event) {
    mouseX = (event.pageX - parseFloat(canvas.style.left, 10)) + document.body.scrollLeft;
    mouseY = (event.pageY - parseFloat(canvas.style.top, 10)) + document.body.scrollTop;
}

document.body.addEventListener("keydown", function (event) {
    switch (event.keyCode) {
        case 70:
            if (canvas.requestFullScreen) {
                canvas.requestFullScreen();
            }
            else if (canvas.webkitRequestFullScreen) {
                canvas.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
            } 
            else if (canvas.mozRequestFullScreen) {
                canvas.mozRequestFullScreen();
            }
        break;
    }
});

function on_fullscreen_change() {
    if(document.mozFullScreen || document.webkitIsFullScreen) {
        canvas.style.position = "absolute";
        canvas.style.left = 0;
        canvas.style.top = 0;
        canvas.style.width = screen.width+"px";
        canvas.style.height = screen.height+"px";
        canvas.width = parseFloat(canvas.style.width, 10);
        canvas.height = parseFloat(canvas.style.height, 10);
    }
    else {
        canvas.style.left = 0;
        canvas.style.top = 0;
        canvas.style.width = "1280px";
        canvas.style.height = "720px";
        canvas.width = parseFloat(canvas.style.width, 10);
        canvas.height = parseFloat(canvas.style.height, 10);
    }
}

document.addEventListener('mozfullscreenchange', on_fullscreen_change);
document.addEventListener('webkitfullscreenchange', on_fullscreen_change);

window.setInterval(function(){

    var context = canvas.getContext('2d');
    context.fillStyle = '#0e6eae';
    context.fillRect(mouseX, mouseY, 150, 100);

}, 10);

function getMouseX(){
    return mouseX;
}

function getMouseY(){
    return mouseY;
}

css

:-webkit-full-screen { width: 100%; height: 100%; background: #000; }

EDIT: You can download test files at http://liveweave.com/g5WLW5

Try adding:

canvas.width = screen.width;
canvas.height = screen.height;

canvas.width and canvas.style.width are two different things. The first resizes the context of the canvas, while the second scales the representation of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM