小智 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)
仅在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)
| 归档时间: |
|
| 查看次数: |
104230 次 |
| 最近记录: |