HTML canvas元素可以通过HTML页面的动态自动调整大小:可能是因为其样式属性设置为百分比值,或者可能是因为它在flex容器内。因此,画布的内容也将调整大小:由于插值,画布的内容看起来模糊(分辨率降低)。
为了最大程度地保持分辨率,必须根据元素的当前像素大小来渲染画布内容。
这个小提琴显示了如何使用功能getComputedStyle来完成此操作:https ://jsfiddle.net/fx98gmu2/1/
setInterval(function() {
var computed = getComputedStyle(canvas);
var w = parseInt(computed.getPropertyValue("width"), 10);
var h = parseInt(computed.getPropertyValue("height"), 10);
canvas.width = w;
canvas.height = h;
// re-rendering of canvas content...
}, 2000); // intentionally long to see the effect
使用setTimeout函数,我将画布的宽度和高度更新为这些属性的计算值。
如小提琴所示,这仅在增加窗口大小时有效。每当窗口大小减小时,画布(flexbox的项目)将保持固定。
将其设置flex-basis
为0,使其通过缩小flex-shrink
,并且不强制使用任何最小宽度:
#canvas {
flex: 1 1 0;
min-width: 0;
}
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
setInterval(function() {
var computed = getComputedStyle(canvas),
w = parseInt(computed.width, 10),
h = parseInt(computed.height, 10);
canvas.width = w;
canvas.height = h;
ctx.clearRect(0, 0, w, h);
ctx.beginPath();
ctx.arc(w/2, h/2, h/2, 0, Math.PI*2, true);
ctx.stroke();
}, 2000); // intentionally long to see the effect
#container {
border: 1px solid blue;
width: 100%;
display: flex;
}
#canvas {
border: 1px solid red;
flex: 1 1 0;
min-width: 0;
height: 150px;
}
<div id="container">
<canvas id="canvas"></canvas>
<div>something else...</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句