Newtz
Newtz

Reputation: 41

How to draw a rect within another one

I got a code that based on user's input, draws a rectangle. I need to create another rect within the first one as shown in the picture below.

https://i.sstatic.net/bPj8P.jpg

I got the following code until now. https://codepen.io/newtz/pen/MWWKRYG

    function draw() {
  context.clearRect(0, 0, canvas.width, canvas.height);

  context.beginPath();
  context.strokeRect(zoomedX(50), zoomedY(50), zoomed(width), zoomed(height));

}

Upvotes: 0

Views: 747

Answers (1)

Barudar
Barudar

Reputation: 570

Each time you draw a rectangle, you can draw a smaller one inside. For example, if the width and height equal 100, then you will call:

context.strokeRect(0, 0, 100, 100);

Then you can draw the smaller rectangle using the previous values:

context.strokeRect(0 + 10, 0 + 10, 100 - 20, 100 - 20);

To allow this, you have to give parameters to your draw() function, so can can make the position and size of the new rectangles vary:

draw()  =>  draw(x, y, width, height)

In your code, declare two variables x and y and assign default values (50 in your code).

Then your draw() function:

function draw() {
  context.clearRect(0, 0, canvas.width, canvas.height);

  context.beginPath();
  context.strokeRect(zoomedX(50), zoomedY(50), zoomed(width), zoomed(height));

}

Change like this:

function draw(x, y, width, height) {      
  context.beginPath();
  context.strokeRect(zoomedX(x), zoomedY(y), zoomed(width), zoomed(height));
}

Now it has parameters. We also need to remove the clearing instruction: this function is designed to draw, only this. Moreover, if you don't remove the clearing line, each drawing will remove previously drawn rectangles.

Finally, call the draw(...) functions in your callbacks:

$width.addEventListener("keyup", function () {
    width = this.value;
    context.clearRect(0, 0, canvas.width, canvas.height);
    draw(x, y, width, height);
    draw(x + 5, y + 5, width - 10, height - 10);
    draw(x + 10, y + 10, width - 20, height - 20);
}, false);

Same for the height. So each time you update the width or the height value, it will draw 3 nested rectangles.

Here's a Fiddle: https://jsfiddle.net/nmerinian/jzeygapL/4/

For the test, I created a drawMultiple(x, y, width, height) function which draws three rectangles:

function drawMultiple(x, y, width, height) {
    draw(x, y, width, height);
    draw(x + 5, y + 5, width - 10, height - 10);
    draw(x + 10, y + 10, width - 20, height - 20);
}

Upvotes: 1

Related Questions