如何使画布完全适应屏幕?

6

我有一个程序,可以通过鼠标拖动在画布上移动对象。然而,我希望画布适应屏幕大小。我不确定如何实现这一点。如果我将画布设置为"width:100%; height:100%;",那么对象就会超出范围。

<!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>

这个回答解决了你的问题吗?HTML Canvas全屏 - ggorlen
这个回答解决了你的问题吗?调整HTML5画布以适应窗口大小 - root
4个回答

8
如何使画布完全适应屏幕?
<!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>

6
你的尝试未能奏效,因为你没有为画布的父级元素(在这种情况下是 body 元素)指定 widthheight。此外,默认情况下,body 元素具有填充或边距。因此,您还应该将其中和。 基于您的尝试的 CSS 解决方案:
html, body {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
}
#canvas {
    width: 100%;
    height: 100%;
}
替代CSS解决方案 您还可以将画布的position设置为fixedabsolute(取决于情况)。如果使用fixed,则它将依赖于window。如果使用absolute,请确保所有祖先元素都没有position:relative,以使其依赖于window,除非最近的具有position:relative的祖先元素相对于window

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

Javascript解决方案

如果使用jQuery:

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

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

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

如果使用原生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 = ...

注意

如果您正在使用CSS解决方案,您可能还想在您的#canvas元素中添加box-sizing: border-box,否则它将略微偏离屏幕。

为什么?请参阅:

  1. css-tricks
  2. W3S
  3. MDN

2
你可以使用 canvas.widthcanvas.height 来代替 canvas.setAttribute('width', window.innerWidth); canvas.setAttribute('height', window.innerHeight);。例如:canvas.width = window.innerWidth; canvas.height = window.innerHeight - Kenzoid

2

这个解决方案不需要使用jquery。

这种方法在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>


0

请尝试以下方法:

document.getElementById("canvas").style.width = screen.width + "px";
document.getElementById("canvas").style.height = screen.height + "px";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接