我有一个最模糊的想法,为什么这段代码不会将矩形置于画布中心。它甚至最终被抽出界限。
请帮帮忙?
document.addEventListener('DOMContentLoaded', drawIllustrations);
function drawIllustrations(e) {
var fixedBody = document.getElementById('FixedBody'),
contextOne = fixedBody.getContext('2d'),
centerX = fixedBody.offsetWidth * 0.5;
contextOne.fillStyle = "#BFFF00";
contextOne.fillRect(centerX - 100,0,200,fixedBody.offsetHeight);
}
答案 0 :(得分:1)
你只需要计算画布的中点,然后根据这些坐标绘制矩形:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="800" height="800" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var recWidth = 200
var recHeight = 200
var xPos = (document.getElementById("myCanvas").width/2) - (recWidth/2);
var yPos = (document.getElementById("myCanvas").height/2) - (recHeight/2);
ctx.fillRect(xPos,yPos,recWidth,recHeight);
</script>
</body>
</html>
&#13;
答案 1 :(得分:0)
要将矩形置于画布中心,您需要知道画布的宽度。那很简单。你的rect的x
将是canvasWidth/2 - rectangleWidth/2
所以在你的情况下:
contextOne.fillRect(fixedBody.width/2 - (200/2), 0, 200, fixedBody.height);
答案 2 :(得分:0)
似乎工作正常:
Extract Method
function drawIllustrations() { const fixedBody = document.getElementById('FixedBody'); const contextOne = fixedBody.getContext('2d'); const centerX = fixedBody.offsetWidth * 0.5;
contextOne.fillStyle = "#BFFF00";
contextOne.fillRect(centerX - 100, 0, 200, fixedBody.offsetHeight);
}
drawIllustrations();
canvas {
border: 1px solid #000;
}
我唯一能看到的东西可能有点奇怪:
<canvas id="FixedBody" width="300" height="200"/>
。如果画布小于该画布,它将会熄灭(尽管仍然居中)。如果您希望矩形始终位于画布内,则可以将宽度和高度设置为相对于画布(例如,大小为75%):
200
function drawIllustrations() { const fixedBody = document.getElementById('FixedBody'); const contextOne = fixedBody.getContext('2d'); const centerX = fixedBody.width * .5;
const centerY = fixedBody.height * .5;
contextOne.fillStyle = "#BFFF00";
contextOne.fillRect(centerX - (fixedBody.width * .75 / 2), centerY - (fixedBody.height * .75 / 2), fixedBody.width * .75, fixedBody.height * .75);
}
drawIllustrations();
canvas {
border: 1px solid #000;
}
唯一的另一件事是,因为在您的示例中,您使用了<canvas id="FixedBody" width="300" height="200"/>
和offsetWidth
而不是offsetHeight
和width
,如果height
有任何内容填充或边框,它会被那么多偏移。通常,在使用画布时,请坚持使用canvas
和width
,因为它们只考虑实际画布的大小,而不是相关的边框和填充。
以下是使用height
和offsetWidth
时所做的大量填充和两方将做的事情的示例(其他一切与上面的示例相同:
offsetHeight
function drawIllustrations() { const fixedBody = document.getElementById('FixedBody'); const contextOne = fixedBody.getContext('2d'); const centerX = fixedBody.offsetWidth * .5;
const centerY = fixedBody.offsetHeight * .5;
contextOne.fillStyle = "#BFFF00";
contextOne.fillRect(centerX - (fixedBody.offsetWidth * .75 / 2), centerY - (fixedBody.offsetHeight * .75 / 2), fixedBody.width * .75, fixedBody.offsetHeight * .75);
}
drawIllustrations();
canvas {
border: 1px solid #000;
padding: 200px 200px 0 0;
}