我必须在矩形内使用画布和输出矩形(矩形的数量取决于我在代码中放入的数量),并且矩形应该很好地适合上一个矩形。我真的对如何使矩形居中并使它们适合先前的矩形感到迷惑。我知道为什么我的输出是这样,但是我不确定从这里开始。这就是我所拥有的,任何帮助将不胜感激!



<!DOCTYPE HTML>
<html>
    <head>
        <script>
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
            	var c = canvas.getContext("2d");  //create HTML5 context object to enable draw methods
				drawNestedRectangles(c, 200, 100, 6, 500, 400, "red");

            };




function drawNestedRectangles(context, whereX, whereY, howMany, width, height, color){

		context.beginPath();
		context.rect(whereX, whereY, width, height);
		context.fillStyle = "white";
		context.fill();

		context.lineWidth = 4;
		context.strokeStyle = color;
		context.stroke();
		for(var i=0; i<howMany - 1; i++) {
			whereX = whereX - 5;
			whereY = whereY - 5;
			width = width - 5;
			height = height - 5;
			context.beginPath();
			context.rect(whereX, whereY, width, height);
			context.fill();
			context.lineWidth = 4;
			context.strokeStyle = color;
			context.stroke();
		}



}
</script>
    </head>
    <body>
        <canvas id="myCanvas" width="800" height="600">
        Your browser doesn't support the HTML5 canvas tag

        </canvas>
    </body>
</html>

最佳答案

您只需要简单地移动矩形的(添加x和y值)并相应地更改宽度和高度,就这样(基本上将其减去5,以使其适合最后一个):

whereX = whereX + 5;
whereY = whereY + 5;
width = width - 10;
height = height - 10;




<!DOCTYPE HTML>
<html>
    <head>
        <script>
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
            	var c = canvas.getContext("2d");  //create HTML5 context object to enable draw methods
				drawNestedRectangles(c, 200, 100, 6, 500, 400, "red");

            };




function drawNestedRectangles(context, whereX, whereY, howMany, width, height, color){


		context.beginPath();
		context.rect(whereX, whereY, width, height);
		context.fillStyle = "white";
		context.fill();

		context.lineWidth = 4;
		context.strokeStyle = color;
		context.stroke();
		for(var i=0; i<howMany - 1; i++) {
			whereX = whereX + 5;
			whereY = whereY + 5;
			width = width - 10;
			height = height - 10;
			context.beginPath();
			context.rect(whereX, whereY, width, height);
			context.fill();
			context.lineWidth = 4;
			context.strokeStyle = color;
			context.stroke();
		}
        context.fillStyle = color;
        context.fillText("Hello", whereX + (width/2) ,
whereY + (height/2));



}
</script>
    </head>
    <body>
        <canvas id="myCanvas" width="800" height="600">
        Your browser doesn't support the HTML5 canvas tag

        </canvas>
    </body>
</html>

09-20 20:41