2
votes

Here is my full code on jsfiddle: https://jsfiddle.net/f5z8qtcp/7/

To reproduce my problem please follow this steps:

  • Click on the red bordered canvas and drag your mouse in order to create a rectangle.

  • Now create another rectangle in another part of the canvas and you will see that the color is same for all the rectangles and change for every one when you create new rectange.

I want get a specific color for each rectangle.

The part of code that change the color is:

function drawAll(){
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  var color_s = 'hsl(' + 360 * Math.random() + ', 50%, 50%)';
  ctx.lineWidth=1;
  ctx.strokeStyle=color_s;
  ctx.fillStyle = color_s;
  for(var i=0;i<rects.length;i++){
    var r=rects[i];
    ctx.strokeRect(r.left,r.top,r.right-r.left,r.bottom-r.top);
    ctx.fillRect(r.left,r.top,r.right-r.left,r.bottom-r.top);
  }
}

This line let us generate random colors :

var color_s = 'hsl(' + 360 * Math.random() + ', 50%, 50%)';

Please correct my false in this code.

EDIT

I solved a part of problem with this small modification:

function drawAll(){
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  for(var i=0;i<rects.length;i++){
    var r=rects[i];
    var color_s = 'hsl(' + 360 * Math.random() + ', 50%, 50%)';
    ctx.lineWidth=1;
    ctx.strokeStyle=color_s;
    ctx.fillStyle = color_s;    
    ctx.strokeRect(r.left,r.top,r.right-r.left,r.bottom-r.top);
    ctx.fillRect(r.left,r.top,r.right-r.left,r.bottom-r.top);
  }
}

But still when i click to create new rectangle, color change for all the other rectangles.

1

1 Answers

3
votes

How about storing your color with coordinates?

newRect={
    left:Math.min(startX,mouseX),
    right:Math.max(startX,mouseX),
    top:Math.min(startY,mouseY),
    bottom:Math.max(startY,mouseY),
    color: undefined
  }

and DrawAll:

    var color_s = rects[i].color ? rects[i].color : 'hsl(' + 360 * Math.random() + ', 50%, 50%)';
    rects[i].color = color_s;

JSFiddle: https://jsfiddle.net/f5z8qtcp/10/