居中画布

use*_*147 53 html css html5 canvas

如何标记一个页面的HTML5 canvas使得canvas

  1. 占据宽度的80%

  2. 具有相应的像素高度和宽度,有效地定义了比例(并且当画布拉伸到80%时按比例保持)

  3. 垂直和水平居中

您可以假设它canvas是页面上唯一的东西,但div如果需要,可以随意将其封装在s中.

小智 37

这将使画布水平居中:

#canvas-container {
   width: 100%;
   text-align:center;
}

canvas {
   display: inline;
}
Run Code Online (Sandbox Code Playgroud)

HTML:

<div id="canvas-container">
   <canvas>Your browser doesn't support canvas</canvas>
</div>
Run Code Online (Sandbox Code Playgroud)


Dan*_*iel 18

看看目前的答案,我觉得缺少一个简单而干净的修复方法.以防有人经过并寻找合适的解决方案.我用一些简单的CSS和javascript非常成功.

将画布居中到屏幕中间或父元素.没有包装.

HTML:

<canvas id="canvas" width="400" height="300">No canvas support</canvas>
Run Code Online (Sandbox Code Playgroud)

CSS:

#canvas {
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin:auto;
}
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

window.onload = window.onresize = function() {
    var canvas = document.getElementById('canvas');
    canvas.width = window.innerWidth * 0.8;
    canvas.height = window.innerHeight * 0.8;
}
Run Code Online (Sandbox Code Playgroud)

像魅力测试的工作:火狐,铬

小提琴:http://jsfiddle.net/djwave28/j6cffppa/3/


小智 9

最简单的方法

将画布放入段落标签中,如下所示:

<p align="center">
  <canvas id="myCanvas" style="background:#220000" width="700" height="500" align="right"></canvas>
</p>
Run Code Online (Sandbox Code Playgroud)


Nic*_*lay 7

仅在Firefox上测试过:

<script>
window.onload = window.onresize = function() {
    var C = 0.8;        // canvas width to viewport width ratio
    var W_TO_H = 2/1;   // canvas width to canvas height ratio
    var el = document.getElementById("a");

    // For IE compatibility http://www.google.com/search?q=get+viewport+size+js
    var viewportWidth = window.innerWidth;
    var viewportHeight = window.innerHeight;

    var canvasWidth = viewportWidth * C;
    var canvasHeight = canvasWidth / W_TO_H;
    el.style.position = "fixed";
    el.setAttribute("width", canvasWidth);
    el.setAttribute("height", canvasHeight);
    el.style.top = (viewportHeight - canvasHeight) / 2;
    el.style.left = (viewportWidth - canvasWidth) / 2;

    window.ctx = el.getContext("2d");
    ctx.clearRect(0,0,canvasWidth,canvasHeight);
    ctx.fillStyle = 'yellow';
    ctx.moveTo(0, canvasHeight/2);
    ctx.lineTo(canvasWidth/2, 0);
    ctx.lineTo(canvasWidth, canvasHeight/2);
    ctx.lineTo(canvasWidth/2, canvasHeight);
    ctx.lineTo(0, canvasHeight/2);
    ctx.fill()
}
</script>

<body>
<canvas id="a" style="background: black">
</canvas>
</body>
Run Code Online (Sandbox Code Playgroud)


Tho*_*yer 0

鉴于画布没有 JavaScript 就什么都不是,也可以使用 JavaScript 来调整大小和定位(你知道:onresizeposition:absolute等)