最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to make canvas 100% fit to the screen? - Stack Overflow

programmeradmin4浏览0评论

I have a program for moving an object on a canvas on mouse drag. However, I want the canvas to fit the screen. I am not sure how to achieve that. If I make the canvas "width:100%; height:100%;", then the object goes out of scope.

<!doctype html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" media="all" href="css/reset.css"/>    <!-- reset css -->
        <script type="text/javascript" src=".min.js">    
        </script>

        <style>
        body{ background-color: ivory; }
        canvas{border:1px solid red;}
    </style>

    <script>
        $(function(){
            var img = new Image();
            img.onload = function(){
                ctx.drawImage(img, 0,0);
            };
            img.src = ".jpg";

            var canvas=document.getElementById("canvas");
            var ctx=canvas.getContext("2d");
            var canvasOffset=$("#canvas").offset();
            var offsetX=canvasOffset.left;
            var offsetY=canvasOffset.top;
            var canvasWidth=canvas.width;
            var canvasHeight=canvas.height;
            var isDragging=false;

     // functions to handle mouseup, mousedown, mousemove, mouseout events

             $("#canvas").mousedown(function(e){handleMouseDown(e);});
             $("#canvas").mousemove(function(e){handleMouseMove(e);});
             $("#canvas").mouseup(function(e){handleMouseUp(e);});
             $("#canvas").mouseout(function(e){handleMouseOut(e);});

        }); // end $(function(){});
    </script>

    </head>

    <body>
        <canvas id="canvas" width=400 height=300></canvas>
    </body>
</html>

I have a program for moving an object on a canvas on mouse drag. However, I want the canvas to fit the screen. I am not sure how to achieve that. If I make the canvas "width:100%; height:100%;", then the object goes out of scope.

<!doctype html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" media="all" href="css/reset.css"/>    <!-- reset css -->
        <script type="text/javascript" src="http://code.jquery.com/jquery.min.js">    
        </script>

        <style>
        body{ background-color: ivory; }
        canvas{border:1px solid red;}
    </style>

    <script>
        $(function(){
            var img = new Image();
            img.onload = function(){
                ctx.drawImage(img, 0,0);
            };
            img.src = "http://images.christmastimeclipart.com/images/2/1271716593176_1788/img_1271716593176_17881.jpg";

            var canvas=document.getElementById("canvas");
            var ctx=canvas.getContext("2d");
            var canvasOffset=$("#canvas").offset();
            var offsetX=canvasOffset.left;
            var offsetY=canvasOffset.top;
            var canvasWidth=canvas.width;
            var canvasHeight=canvas.height;
            var isDragging=false;

     // functions to handle mouseup, mousedown, mousemove, mouseout events

             $("#canvas").mousedown(function(e){handleMouseDown(e);});
             $("#canvas").mousemove(function(e){handleMouseMove(e);});
             $("#canvas").mouseup(function(e){handleMouseUp(e);});
             $("#canvas").mouseout(function(e){handleMouseOut(e);});

        }); // end $(function(){});
    </script>

    </head>

    <body>
        <canvas id="canvas" width=400 height=300></canvas>
    </body>
</html>
Share Improve this question edited Oct 28, 2017 at 9:22 Sushin Pv 1,8944 gold badges25 silver badges36 bronze badges asked Oct 28, 2017 at 8:17 parthibaraj rajasekarparthibaraj rajasekar 551 gold badge1 silver badge5 bronze badges 2
  • Does this answer your question? HTML Canvas Full Screen – ggorlen Commented Feb 16, 2021 at 15:15
  • Does this answer your question? Resize HTML5 canvas to fit window – root Commented Jul 9, 2023 at 13:15
Add a comment  | 

4 Answers 4

Reset to default 8

how to make canvas 100% fit to the screen?

<!doctype html>
<html>
<head>
    <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
    <!-- reset css -->
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: ivory;
        }

        #canvas {
            position: absolute;
            width: 100%;
            height: 100%;
            border: 1px solid red;
        }
    </style>
    <script>
        $(function () {
            var img = new Image();
            img.onload = function () {
                ctx.drawImage(img, 0, 0);
            };
            img.src =
                "http://images.christmastimeclipart.com/images/2/1271716593176_1788/img_1271716593176_17881.jpg";

            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");
            var canvasOffset = $("#canvas").offset();
            var offsetX = canvasOffset.left;
            var offsetY = canvasOffset.top;

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

            /*var canvasWidth=canvas.width;
            var canvasHeight=canvas.height;*/

            var isDragging = false;

            // functions to handle mouseup, mousedown, mousemove, mouseout events

            $("#canvas").mousedown(function (e) {
                handleMouseDown(e);
            });
            $("#canvas").mousemove(function (e) {
                handleMouseMove(e);
            });
            $("#canvas").mouseup(function (e) {
                handleMouseUp(e);
            });
            $("#canvas").mouseout(function (e) {
                handleMouseOut(e);
            });

        }); // end $(function(){});
    </script>
</head>
<body>
    <canvas id="canvas"></canvas>
</body>
</html>

Your attempt is not working because you did not specify a width and height to the canvas's parent (in this case, the body element). Also, by default, body element has a padding or margin. So you should neutralize it too.

CSS solution based on your attempt:

html, body {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
}
#canvas {
    width: 100%;
    height: 100%;
}

Alternative CSS Solution

You can also set canvas's position to fixed or absolute (depending on circumstances). If you use fixed, it will depend on the window. If you use absolute, make sure all its ancestors don't have position: relative to make it dependent on window unless its nearest ancestor with position: relative is relative to the window.

#canvas {
    position: fixed; /* absolute */
    top: 0;
    left: 0;
    width: 100vw;    /* 100% */
    height: 100vh;   /* 100% */
}

Javascript Solution

If using jQuery:

var $canvas = $('#canvas'),
    $window = $(window);

$canvas.attr({
    width: $window.width(),
    height: $window.height()
});

// Or use $canvas.css({...});

If using vanilla JavaScript:

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

canvas.setAttribute('width', window.innerWidth);
canvas.setAttribute('height', window.innerHeight);

// Or use canvas.style.width = ... and canvas.style.height = ...

NOTE

If you are using CSS solutions, you might want to add box-sizing: border-box to your #canvas element too or it will render slightly off the screen.

Why? Read at:

  1. css-tricks
  2. W3S
  3. MDN

This solution is without jquery.

This method does not work below IE8:

/**
 * @author TessavWalstijn. GitHub: https://github.com/TessavWalstijn
 * Sets the canvas properties.
 * @param {object} Cvs Give the html canvas Id.
 * @param {boolean} Fullscreen Change the canvas fullscreen default false.
 * @param {string} Dimension Change the canvas dimension default "2d".
 * @return {object}
 */
function NewCanvas(cvs, fullscreen, dimension) {
    if (!dimension) dimension = "2d";
    var ctx = cvs.getContext(dimension);
    if (fullscreen) {
        cvs.style.position = "fixed";
        cvs.style.left = cvs.x = 0;
        cvs.style.top = cvs.y = 0;
    } else {
        var rect = cvs.getBoundingClientRect();
        cvs.x = rect.left;
        cvs.y = rect.top;
    }
    cvs.ctx = ctx;
    cvs.dimension = dimension;
    cvs.fullscreen = fullscreen;
    return cvs;
}

/**
 * @author TessavWalstijn. GitHub: https://github.com/TessavWalstijn
 * Updates the canvas width and hight.
 * @param {object} Cvs NewCanvas() object.
 * @param {boolean} Clear Change the canvas clear default true.
 */
function UpdateCvs(cvs, clear = true) {
    if (cvs.fullscreen) {
        //if the width is not the same resize the canvas width
        if (window.innerWidth != cvs.width) {
            cvs.width = window.innerWidth;
        }
        //if the height is not the same resize the canvas height
        if (window.innerHeight != cvs.height) {
            cvs.height = window.innerHeight;
        }
    } else {
        let rect = cvs.getBoundingClientRect();
        cvs.x = rect.left;
        cvs.y = rect.top;
    }
    if (cvs.dimension == "2d")
        if (clear)
            cvs.ctx.fillRect(0, 0, cvs.width, cvs.height);
}

/**
 * @author TessavWalstijn. GitHub: https://github.com/TessavWalstijn
 * get html element by id.
 * @param {string} id give the html element id.
 * @return {object} document.getElementById(id);
 */
function GetId(id) { return document.getElementById(id) }

// To create your canvas object.
var canvas = NewCanvas(GetId("yourCanvasId"), true);

// If you want to update your canvas size use this:
window.addEventListener("resize", function() {
    UpdateCvs(canvas);
});

// Set it to current width
UpdateCvs(canvas);
<canvas id="yourCanvasId"><canvas>

Try the following:

document.getElementById("canvas").style.width = screen.width + "px";
document.getElementById("canvas").style.height = screen.height + "px";
发布评论

评论列表(0)

  1. 暂无评论