我是html和JavaScript的新手,但正如标题所述,我遇到了一个问题。似乎我的画布的右侧位于我创建的canvas-wrap div的中心。我尝试了许多不同的方法来使此画布居中无济于事。帮助PLZ!
链接到它的外观 https://imgur.com/a/HgBQImo
这只是用html和js显示在网页上的简单画布。我尝试使用js解决方案根据视口的高度/宽度以及该网站上的许多常见CSS技术来使画布居中。
<!DOCTYPE html>
<html>
<head>
<title>First Game basics</title>
<meta name="veiwport" content= "width=device-width">
<style>
* {box-sizing: border-box; margin:0; padding: 0;}
html {
height: 100%;
width: 100%;
}
body {
background-color: #202888;
color: #fff;
font-family: monospace;
font-size: 1.25em;
min-height: 100%;
width: 100%;
}
canvas {
}
div.canvas-wrap {
width: 80%;
height: 80%;
border: 1px solid red;
margin: 0px auto;
text-align: center;
}
</style>
</head>
<body>
<p>Learn some<br>basic canvas<br>manipulation</p>
<div class="canvas-wrap">
<canvas>Canvas not supported</canvas>
</div>
<script type="text/javascript">
const ctx = document.querySelector('canvas').getContext('2d');
ctx.fillStyle = "#008000";
ctx.fillRect(0, 0, ctx.canvas.height, ctx.canvas.width);
</script>
</body>
</html>
答案 0 :(得分:0)
一切正常。你只是画错了...
fillRect参数为(x,y,width,height),但是您倒数了最后2个,并且正在绘制(x,y,height,width),因此您正在画布上绘制。
与
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
它将起作用。
另外,使用检查器查看DOM元素的位置,您会在2秒内看到错误