使用100%不会使我的画布填满窗口

时间:2015-08-06 01:41:55

标签: javascript html css canvas fullscreen

我试图让我的画布填满整个窗口。将宽度和高度设置为100%根本不起作用。相反,它使它成为100px×100px。为什么会发生这种情况,我怎样才能达到效果?

这是一个基本上显示我的问题的小提琴。谢谢!

https://jsfiddle.net/t04n6q9y/1/

<body height="100%" width="100%">
    <canvas id="myCanvas" width="100%" height="100%"></canvas>
</body>

3 个答案:

答案 0 :(得分:0)

宽度和高度是属性,不支持100%它们必须是绝对的。如果您在CSS中提供var height = window.innerHeight; var width = window.innerWidth; var canvas = document.getElementById('myCanvas'); canvas.height = height; 宽度和高度,则您的画布不会缩放到var height = window.innerHeight; var width = window.innerWidth; var canvas = document.getElementById('myCanvas'); canvas.height = height; canvas.width = width; var context = canvas.getContext('2d'); context.fillStyle = "#FFFF00"; context.fillRect(0, 0, canvas.width, canvas.height);,而是会缩放到100%。我建议采用以下方法来实现100%的宽度和高度:

您需要在javascript中计算宽度,然后应用它Fiddle

JS:

body {
  margin: 0px;
  padding: 0px;
  background-color: #00000F
}
canvas {
  padding: 0;
  margin: auto;
  display: block;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

段:

&#13;
&#13;
<body>
  <canvas id="myCanvas"></canvas>
</body>
&#13;
public void getSuccessor(DirectedGraph<Point, DefaultEdge> graph, Point point, String type, int depth) {
    List<Point> visitedPoints = new ArrayList<>();
    _getSuccessor(graph, point, visitedPoints, type, depth);
}

private void _getSuccessor(DirectedGraph<Point, DefaultEdge> graph, Point point, List<Point> visitedPoints, String type, int depth){

    if(depth == 0)
        return;

    // Mark node as visited
    visitedPoints.add(point);

    // Loop on all its successors
    for(Point successor : Graphs.successorListOf (directedGraph, point)){

        // If node not already visited
        if(!visitedPoints.contains(successor) && successor.type.equals(type)) {
            directedGraph.addEdge(firstPoint, successor);
            _getSuccessor(graph, successor, visitedPoints, type, depth-1);
        }
    }
}
&#13;
{{1}}
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

您应该使用CSS而不是HTML标记属性来执行此操作。通过声明CSS类,您将能够将此相同的样式应用于您可能想要全屏的其他任何内容。它还将DOM逻辑与样式逻辑分开。

我将如何做到这一点:

<强> HTML:

<canvas class="fullscreen"></canvas>

<强> CSS:

canvas.fullscreen {
  width: 100vw;
  height: 100vh;
}

“vw”和“vh”单位分别代表视图宽度和视图高度的百分比。使用这些单位将确保您的画布填充整个视口,而不管其父元素的大小。

答案 2 :(得分:-1)

所有需要做的就是画布有一个要扩展的元素。

HTML:

<body>
    <div id="canback">
    <canvas id="myCanvas"></canvas>
    </div>
</body>

CSS:

body {
margin: 0px;
padding: 0px;
background-color: #00000F
}

#canback {
height: 100%;
width: 100%;
margin: 0 auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}

#myCanvas {
background:#f4f4f4;
height:100%;
width: 100%;
padding: 0;
margin: 0 auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}

这是Fiddle

我希望这有帮助。 :d