Canvas: Clipping, Masking, Pattern

Clipping:

Clipping is a way to hide unwanted parts of the shape. It just uses geometrical shapes to define the clip area, with no style effects. I2Djs createClip() API, lets you define the clip area as shown below.

var clipInstance = renderer_.createClip();
clipInstance.clip.createEl({
	el: 'polygon',
	attr:{
		points: [{x: 0, y: 0}, {x: 0, y: 100}, {x: 100, y: 100}, {x: 100, y: 0}, {x: 0, y: 0}]
	}
});

ClipInstance to be applied to the shape via 'clip-Path' style property as given below.

g.createEl({
	el: 'circle',
	attr: {
		cx: 100,
		cy: 100,
		r: 100
	},
	style: {
		'clip-Path': clipInstance,
		strokeStyle: 'grey',
		fillStyle: 'green'
	}
});

Masking:

Masking is a way to apply complex, detailed shapes with styles on the elements. With the masking technique, one can implement beautiful visual effects and performant alternatives to other techniques.

I2Djs createMask() API to create mask instance. globalCompositeOperation of the maskInstance can be altered to leverage Canvas multi masking composition to create different effects. By default it is set to - 'destination-atop' composition.

Below example shows a way to define the mask using I2Djs createMask().

var maskInstance = renderer_.createMask();
maskInstance.mask.createEl({
	el: 'rect',
	attr:{
		x: 0,
		y: 0,
		width: 566,
		height: 200
	},
	style: {
		fillStyle: pattern2
	}
});

Maskinstance to be applied as a mask style property on the element as shown below.

renderer_1.createEl({
	el: 'image',
	attr: {
		src: './../../i2djsLogo.png',
		x: 0,
		y: 0,
		width: 566,
		height: 300
	},
	style: {
		mask: maskInstance
	}
});

Pattern:

Last updated