繁体   English   中英

画布:2个矩形相交处的颜色

[英]Canvas : color in intersection of 2 rectangles

我有一块画布。

在此画布中,我必须绘制一个带有红色矩形的网格:

首先,我画垂直矩形

-然后,我画水平矩形

每个矩形都具有相同的不透明度(0.3)。

通常,由于重叠,两个矩形相交处的颜色必须更红色。

因此渲染必须是这样的:

在此处输入图片说明

但是我的代码不起作用,因为相交处的颜色不是红色,颜色与矩形相同(您可以尝试: 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>

所以有什么问题 ?

你快到了 但是通过使用ctx.rect()ctx.fill() ,可以一次绘制整个形状,并且不应用“叠加”。

您可以通过以下方式轻松修复它:

  • 更换ctx.rect()与调用ctx.fillRect()
  • 删除不相关的ctx.fill()

这是固定的JSFiddle

替代方法

您还可以使用两个不同的路径,但是需要使用.beginPath()方法清楚地对其进行限制: 如下所示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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