how to draw multiple square using a loop to change the position only in java script?

225 Views Asked by At

I am trying to use a button that can build a small square every time I click it with changing only position x

this is the code but it doesn't draw a square instead it's drawing a long rectangle

let addBlock = document.getElementById('addBlock')
var c = document.getElementById('canvas1');
var ctx = c.getContext("2d");
let s =0;
for(let i=0; i<=100; i=i+5 ){
addBlock.addEventListener('click', function(){
        ctx.beginPath();
        ctx.rect(10+i, 20,9, 100);
        ctx.fill()
         s=s+i;   })}
2

There are 2 best solutions below

0
Chris On
rect(x,y,height,width)

I think you just need to change the width from 100 to 9.

ctx.rect(10+i, 20, 9, 9);
2
timmmmmb On

if i understood the purpose of your application correctly then you want to change the position on each click. Your code doesnt work because the foorloop finishes before you even get to click once. My solution is the following:

let addBlock = document.getElementById('addBlock');
var c = document.getElementById('canvas1');
var ctx = c.getContext('2d');
let i = 0;

let fn = function() {
  ctx.clearRect(0, 0, c.width, c.height);
  ctx.beginPath();
  ctx.rect(20 + i, 20, 100, 100);
  ctx.fill();
  i += 5;
  addBlock.addEventListener('click', fn);
};

addBlock.addEventListener('click', fn);

See my Stackblitz link for a working example: https://stackblitz.com/edit/web-platform-4dhxpt?file=script.js

EDIT:

changed the code to run a maximum of 20 times:

let fn = function() {
  if (i >= 100) {
    return;
  }
  ctx.beginPath();
  ctx.rect(20 + i, 20, 100, 100);
  ctx.fill();
  i += 5;
  addBlock.addEventListener('click', fn);
};