I wanted to show circular cropped image in my canvas and I'm using konvajs. Is there any way to do it in konva itself or is there any workarounds with JS/CSS?
This is the code I use for loading the image.
var src = 'https://konvajs.github.io/assets/yoda.jpg';
Konva.Image.fromURL(src, function(yoda) {
console.log(yoda);
yoda.setAttrs({
x: 10,
y: 10,
width: 180,
height: 180
});
group.add(yoda);
layer.batchDraw();
});
Actually there is a way offered by konva itself. To do this, you have to define a clipping region either for a konva layer or a group. This clipping region can be as simple as a rectangle or something more advanced like a circle.
The shape is set using the clipFunc
property of a layer or group. This property expects a function which contains a set of drawing operations to define your actual shape. So in case of a circle, you would utilize the context.arc()
operation.
Here's an example:
var src = 'https://picsum.photos/id/237/200/300';
var stage = new Konva.Stage({
container: 'container',
width: 400,
height: 300,
});
var layer = new Konva.Layer({
clipFunc: function(ctx) {
ctx.arc(130, 140, 70, 0, Math.PI * 2, false);
}
});
stage.add(layer);
Konva.Image.fromURL('https://picsum.photos/id/237/200/300', function(theDog) {
theDog.setAttrs({
x: 0,
y: 0,
scaleX: 1,
scaleY: 1,
});
layer.add(theDog);
layer.batchDraw();
});
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<div id="container"></div>