1
我必须在矩形内使用画布和输出矩形(矩形的数量取决于我在代码中放置了多少),矩形应该很好地适合前一个矩形。我真的失去了如何居中矩形,并让它们适合在前面的矩形内。我知道为什么我的输出是这样,但我不知道该从哪里出发。这是我的,任何帮助将不胜感激!使用画布在矩形内绘制矩形?
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function(){
var canvas = document.getElementById("myCanvas");
\t var c = canvas.getContext("2d"); //create HTML5 context object to enable draw methods
\t \t \t \t drawNestedRectangles(c, 200, 100, 6, 500, 400, "red");
\t \t \t
}; \t \t
\t \t \t
\t \t \t \t
\t \t \t \t
function drawNestedRectangles(context, whereX, whereY, howMany, width, height, color){ \t
\t \t \t
\t \t context.beginPath();
\t \t context.rect(whereX, whereY, width, height);
\t \t context.fillStyle = "white";
\t \t context.fill();
\t \t
\t \t context.lineWidth = 4;
\t \t context.strokeStyle = color;
\t \t context.stroke();
\t \t for(var i=0; i<howMany - 1; i++) {
\t \t \t whereX = whereX - 5;
\t \t \t whereY = whereY - 5;
\t \t \t width = width - 5;
\t \t \t height = height - 5;
\t \t \t context.beginPath();
\t \t \t context.rect(whereX, whereY, width, height);
\t \t \t context.fill();
\t \t \t context.lineWidth = 4;
\t \t \t context.strokeStyle = color;
\t \t \t context.stroke();
\t \t }
\t \t \t \t \t \t \t \t
\t \t \t
\t \t \t
}
</script>
</head>
<body>
<canvas id="myCanvas" width="800" height="600">
Your browser doesn't support the HTML5 canvas tag
\t
</canvas>
</body>
</html>
@JamesC。是的,我们只需要:'context.fillText(“Hello”,whereX +(width/2),whereY +(height/2))''。基本上将文本放在主三角形的中心位置与放置在最后一个三角形的中心位置相同。我已经更新了我的问题,在中间添加了文字。 –