如何自动缩放HTML5 <canvas>元素以适应页面?
例如,我可以得到一个<div>通过设置高度和宽度属性为100%缩放,但一个<canvas>不会缩放,会吗?
如何自动缩放HTML5 <canvas>元素以适应页面?
例如,我可以得到一个<div>通过设置高度和宽度属性为100%缩放,但一个<canvas>不会缩放,会吗?
当前回答
CSS
body { margin: 0; }
canvas { display: block; }
JavaScript
window.addEventListener("load", function()
{
var canvas = document.createElement('canvas'); document.body.appendChild(canvas);
var context = canvas.getContext('2d');
function draw()
{
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(0, 0); context.lineTo(canvas.width, canvas.height);
context.moveTo(canvas.width, 0); context.lineTo(0, canvas.height);
context.stroke();
}
function resize()
{
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
draw();
}
window.addEventListener("resize", resize);
resize();
});
其他回答
我相信我已经找到了一个优雅的解决方案:
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;
}
到目前为止,还没有对我的表现产生任何大的负面影响。
(function() {
// get viewport size
getViewportSize = function() {
return {
height: window.innerHeight,
width: window.innerWidth
};
};
// update canvas size
updateSizes = function() {
var viewportSize = getViewportSize();
$('#myCanvas').width(viewportSize.width).height(viewportSize.height);
$('#myCanvas').attr('width', viewportSize.width).attr('height', viewportSize.height);
};
// run on load
updateSizes();
// handle window resizing
$(window).on('resize', function() {
updateSizes();
});
}());
除非你想让画布自动提升你的图像数据(这就是James Black的答案,但它看起来不漂亮),你必须自己调整它的大小并重新绘制图像。画布居中
设置初始大小。
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);
使用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;">