totoaussi totoaussi - 3 months ago 20
Javascript Question

Canvas : color in intersection of 2 rectangles

I have a canvas.

In this canvas, I must draw a grid with red rectangles :

-firstly, I draw vertical rectangles,

-then, I draw horizontal rectangles

Every rectangle have the same opacity (0.3).

Normally, the color in intersection of 2 rectangles must be more red because of the superposition.

So the render must be like this :

enter image description here

But my code doesn't work because the color in intersection isn't more red, the color is the same than a rectangle (you can try it : https://jsfiddle.net/6urj27ua/) :

<canvas id="canvas"></canvas>

<script type="text/javascript">

//The canvas :
c = document.getElementById("canvas");
c.style.border = "solid #000000 1px";

//Size of canvas :
c.width = 300;
c.height = 300;

//The canvas context :
ctx = c.getContext("2d");


//Drawing function :
function draw()
{
//Clear the drawing :
ctx.clearRect(0, 0, c.width, c.height);

/*Define size of a rect :*/
width_rect = 20;
height_rect = 200;

/*Fill color for rect :*/
ctx.fillStyle = "rgba(255, 0, 0, 0.3)";

/*Draw 5 vertical rectangles :*/
for(i = 0; i <= 5 ; i++)
{
ctx.rect(i*(width_rect*2), 0, width_rect, height_rect);
}

/*Draw 5 horizontal rectangles :*/
for(i = 0; i <= 5 ; i++)
{
ctx.rect(0, i*(width_rect*2), height_rect, width_rect);
}

ctx.fill();
}


//Draw :
setInterval("draw()", 300);

</script>


So what's the problem ?

Answer

You are almost there. But by using ctx.rect() and ctx.fill(), the whole shape is drawn at once and no 'superposition' is applied.

You can easily fix it by:

  • replacing ctx.rect() calls with ctx.fillRect()
  • removing the ctx.fill() which becomes irrelevant

Here is a fixed JSFiddle.

Alternate method

You could also use two distinct paths, but you'd need to clearly circumscribe them with the .beginPath() method: like this.

Comments