如何自动缩放HTML5 <canvas>元素以适应页面?
例如,我可以得到一个<div>通过设置高度和宽度属性为100%缩放,但一个<canvas>不会缩放,会吗?
如何自动缩放HTML5 <canvas>元素以适应页面?
例如,我可以得到一个<div>通过设置高度和宽度属性为100%缩放,但一个<canvas>不会缩放,会吗?
当前回答
设置初始大小。
const canvas = document.getElementById('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
更新窗口大小调整。
function windowResize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
window.addEventListener('resize', windowResize);
其他回答
一个最小的设置
HTML
<canvas></canvas>
CSS
html,
body {
height: 100%;
margin: 0;
}
canvas {
width: 100%;
height: 100%;
display: block;
}
JavaScript
const canvas = document.querySelector('canvas');
const resizeObserver = new ResizeObserver(() => {
canvas.width = Math.round(canvas.clientWidth * devicePixelRatio);
canvas.height = Math.round(canvas.clientHeight * devicePixelRatio);
});
resizeObserver.observe(canvas);
对于 WebGL
const canvas = document.querySelector('canvas');
const gl = canvas.getContext('webgl');
const resizeObserver = new ResizeObserver(() => {
canvas.width = Math.round(canvas.clientWidth * devicePixelRatio);
canvas.height = Math.round(canvas.clientHeight * devicePixelRatio);
gl.viewport(0, 0, canvas.width, canvas.height);
});
resizeObserver.observe(canvas);
注意,我们应该考虑到设备像素比,特别是对于HD-DPI显示。
使用jQuery,您可以跟踪窗口调整大小和改变画布的宽度使用jQuery以及。
就像这样
$(window).resize(function() { $ (" # myCanvas”)。Width ($(window).width()) }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
我相信我已经找到了一个优雅的解决方案:
JavaScript
/* important! for alignment, you should make things
* relative to the canvas' current width/height.
*/
function draw() {
var ctx = (a canvas context);
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
//...drawing code...
}
CSS
html, body {
width: 100%;
height: 100%;
margin: 0;
}
到目前为止,还没有对我的表现产生任何大的负面影响。
除非你想让画布自动提升你的图像数据(这就是James Black的答案,但它看起来不漂亮),你必须自己调整它的大小并重新绘制图像。画布居中
根据浏览器客户机的尺寸设置画布坐标空间的宽度和高度需要您在浏览器调整大小时重新调整大小和绘制。
一个不那么复杂的解决方案是在Javascript变量中维护可绘制的尺寸,但根据屏幕设置画布尺寸。宽度、屏幕。高度尺寸。使用CSS来适应:
#containingDiv {
overflow: hidden;
}
#myCanvas {
position: absolute;
top: 0px;
left: 0px;
}
浏览器窗口通常不会比屏幕本身大(除非屏幕分辨率被误报,因为它可能是不匹配的双显示器),所以背景不会显示,像素比例也不会变化。画布像素将与屏幕分辨率成正比,除非你使用CSS缩放画布。