How to apply transparency for several shapes at once?

Is it possible to use opacity for several shapes in the same time?

You can use opacity attribute to change alpha channel of any Konva node. In the way the canvas works, all shapes have its own independent opacity values.

That mean if you have a group with several shapes inside and that group have group.opacity(0.5). It will look exactly the same as if each shape inside the group has shape.opacity(0.5) and the group have group.opacity(1). That means you will see overlapping areas of that shapes.

What if we don’t want to see overlapping areas of transparent shapes?

There is a way to fix such default behavior. You just need to cache the group with group.cache(). Caching the group will convert it into bitmap and draw into external canvas. On the next draw call, Konva will use that resulted canvas to draw whole group with opacity applied to whole image.

So while Konva is making a bitmap cache for such group it will draw internal shapes ignoring transparency of the group.

Remember that if a group is cached, it has some limitations of cached nodes. Like if you are doing any internal changes (like changing shapes attributes) you have to recache the group. And that is expensive operation, so it is not recommended to do it frequently like inside animations or on every mousemove.

Instructions: on the left you see default behavior, on the right you see fixed behavior with cached group.

Konva transparent groupview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Transparency for several Shapes Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background: #f0f0f0;
background: linear-gradient(
115deg,
transparent 75%,
rgba(255, 255, 255, 0.8) 75%
)
0 0,
linear-gradient(245deg, transparent 75%, rgba(255, 255, 255, 0.8) 75%)
0 0,
linear-gradient(115deg, transparent 75%, rgba(255, 255, 255, 0.8) 75%)
7px -15px,
linear-gradient(245deg, transparent 75%, rgba(255, 255, 255, 0.8) 75%)
7px -15px,
#f0f0f0;
background-size: 15px 30px;
}
</style>
</head>

<body>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;

var stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
});

var layer = new Konva.Layer();
stage.add(layer);

// lets create default group with two overlapping shapes
var group1 = new Konva.Group({
opacity: 0.5,
x: 50,
y: 50,
draggable: true,
});
group1.add(
new Konva.Rect({
width: 100,
height: 100,
fill: 'red',
})
);
group1.add(
new Konva.Circle({
x: 100,
y: 100,
radius: 70,
fill: 'greed',
})
);
layer.add(group1);

// lets create the second group
var group2 = group1.clone({ x: 250 });
layer.add(group2);

// to change opacity behavior we have to fix whole group
group2.cache();

layer.draw();
</script>
</body>
</html>
Enjoying Konva? Please consider to support the project.