html - 在canvas中,如何绘制2个半透明重叠的圆圈

标签 html canvas

我想在 HTML Canvas 的灰色矩形上绘制两个圆圈。

我尝试了以下步骤:

  1. 将矩形填充为灰色

  2. 更改 globalComposition 打火机以混合两种颜色。

我只想混合蓝色和红色,而不是灰色和灰色矩形。

enter image description here

最佳答案

您可以通过 rgba 中的圆圈填充样式轻松实现此属性,其中最后一个参数为 alpha 或不透明度。语法将是这样的

circle.fillStyle = "rgba(255, 255, 255, 0.5)";
//can be used to fill as red object with opacity of 0.5

达到预期效果的完整代码将是这样的。

 // JavaScript Code

 var canvas = document.getElementById('myCanvas');
 var context = canvas.getContext('2d');
 var centerleftX = canvas.width / 4;
 var centerRightX = 3 * canvas.width / 4;
 var centerY = canvas.height / 2;
 var radius = 70;

 context.beginPath();
 context.rect(0, 0, 400, 200);
 context.fillStyle = 'rgb(200,200,200)';
 context.fill();
 context.lineWidth = 7;
 context.strokeStyle = 'black';
 context.stroke();


 context.beginPath();
 context.arc(centerleftX + 50, centerY, radius, 0, 2 * Math.PI, false);
 context.fillStyle = "rgba(0, 0,255,0.7)";
 context.fill();


 context.beginPath();
 context.arc(centerRightX - 50, centerY, radius, 0, 2 * Math.PI, false);
 context.fillStyle = "rgba(255, 0,0,0.7)";
 context.fill();
 
 <!-- HTML Code -->
<canvas id="myCanvas" width="400" height="200">

关于html - 在canvas中,如何绘制2个半透明重叠的圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26114693/

相关文章:

html - 有没有办法强制下拉(选择)箭头控件位于右侧?

javascript - Canvas ,禁用图像下载

php - 如何将自己的内置函数添加到php源代码中?

html - 隐藏其他框阴影的背景颜色

html - div 中的图像在图像下方有额外的空间

javascript - 在保留图像的同时在 HTML5 Canvas 中绘制图像

canvas - 神秘 flutter 警告 : Element is implicitly hidden?

javascript - 在旋转的 CANVAS 上绘图 - 第 2 部分

javascript - 在 FabricJs 中使用 localStorage 对象重绘 Canvas

javascript - 在 Semantic-ui 中使用 'segment' 元素内的列