Skip to main content

HTML5 Canvas Blend mode with globalCompositeOperation Tutorial

globalCompositeOperation Documentation.

With Konva framework you can set globalCompositeOperation or blending mode operations with globalCompositeOperation property.

Instructions: Drag the red rectangle over the green text to see the XOR blending effect.

import Konva from 'konva';

const stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight
});

const layer = new Konva.Layer();

const text = new Konva.Text({
text: 'Text Shadow!',
fontFamily: 'Calibri',
fontSize: 40,
x: 20,
y: 20,
fill: 'green',
shadowColor: 'white',
shadowOffset: { x: 10, y: 10 }
});
layer.add(text);

const rect = new Konva.Rect({
x: 50,
y: 50,
width: 100,
height: 100,
fill: 'red',
draggable: true,
globalCompositeOperation: 'xor'
});

layer.add(rect);
stage.add(layer);

Blending inside a group​

A shape's blend mode mixes it with everything already drawn on its layer. To blend shapes only with each other, put them in a group with isolated: true (Konva 10.7.0 or newer). The group's own globalCompositeOperation then blends the combined result with the content below:

const group = new Konva.Group({
isolated: true,
// blends the whole group with the layer below it
globalCompositeOperation: 'multiply',
});
// blends only with the shapes drawn before it in this group
shape.globalCompositeOperation('xor');
group.add(background, shape);

See Isolated Groups for a live demo.