简体   繁体   中英

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 :

在此处输入图片说明

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 ?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM