我正在练习 javascript,我正在尝试制作一个游戏。我希望画布元素是全屏的,因此我对高度和宽度属性使用了百分比,但是当我这样做时,它的行为与通常不同。当我运行调试代码时,它应该生成一个 50px x 50px 的盒子,但图形看起来比正常情况大。
我尝试获取画布的高度和宽度(以像素为单位),但这不起作用。它不会报告任何错误消息,但它仍然太大。
<!DOCTYPE html>
<html>
<head></head>
<body>
<canvas id="canvas" style="height: 100%; width:100%;"></canvas>
</body>
<style>
html, body {width: 100%;
margin: 0;
height: 100%;
overflow: hidden;
position:fixed;}
</style>
<script>
var canvas = document.getElementById("canvas")
var c = canvas.getContext("2d")
c.fillStyle = "#FFFF00"
c.fillRect(50,50,50,50)
</script>
没有任何错误消息出现,但它的大小不正确,我不明白为什么它不起作用。
如果在 CSS 中设置画布大小或使用元素属性设置画布大小,则会有所不同。
画布元素的大小由其设置width
and height
属性(作为数字)。这设置了用于在内存中存储画布绘图的可寻址像素数。在没有宽度和高度属性的情况下,画布元素尺寸设置为 300 x 150(像素)default https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas.
应用于画布的 CSS 可以使用将画布视为图像的软件插值来缩放其尺寸。正如小图像在缩放到全屏时看起来更大一样,300 x 150 像素画布和在其中绘制的对象(使用画布像素坐标)在放大时看起来更大。
要使画布坐标与屏幕尺寸(以像素为单位)匹配,请设置其width
and height
像素数值的属性。例如。
var canvas = document.getElementById("canvas")
var c = canvas.getContext("2d")
c.fillStyle = "#FFFF00"
c.fillRect(50,50,50,50)
console.log( canvas.width, canvas.height);
alert( "fix?" )
canvas.style=""; // remove CSS scaling
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
c.fillStyle = "#FFFF00"
c.fillRect(50,50,50,50)
body {
width: 100%;
margin: 0;
height: 100%;
background-color: honeydew;
overflow: hidden;
position:fixed;
}
canvas {
background-color: silver;
}
<canvas id="canvas" style="height: 100%; width:100%;"></canvas>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)