Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

konvajs - How to add corner radius on konva group using clip function?

I'm struggling to apply corner radius (on all sides) in a group shape using a custom clip function.

Here's my codesandbox:

https://codesandbox.io/s/w28nrrj885

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I copied your clipSquare function into the plain JS snippet below to test your assumptions. It's all good.

Looking further into your code the issue is that you are using the same x,y,w,h values in the definition of the group clip function as you use for the definition of the canvas. This has the effect of making the group overflow off the right and bottom edges of the canvas and so hides the rounded corners.

If you alter your code from

this.clipSquare(ctx, x, y, width, height, 30);`

to

this.clipSquare(ctx, 0, 0, width-x, height-y, 30);

then you will see all 4 corners.

I will leave this snippet in place for future readers as it illustrates the clipfunc in plain JS.

// The following variables define the position on the rect and clipping region
var oX = 20, oY = 10, oW = 300, oH = 200, radius = 30;

var stage = new Konva.Stage({container: 'container', width: 500, height: 300})
var layer = new Konva.Layer();
stage.add(layer)
var rect1 = new Konva.Rect({ x: oX, y: oY, width: oW, height: oH, fill: 'cyan'})
var rect2 = new Konva.Rect({ x: oX, y: oY, width: oW, height: oH, fill: 'magenta'})


var  clipSquare = function(ctx, x, y, width, height, radius)  {
    ctx.beginPath();
    ctx.moveTo(x + radius, y);
    ctx.lineTo(x + width - radius, y);
    ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
    ctx.lineTo(x + width, y + height - radius);
    ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
    ctx.lineTo(x + radius, y + height);
    ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
    ctx.lineTo(x, y + radius);
    ctx.quadraticCurveTo(x, y, x + radius, y);
    ctx.closePath();
  };
  
var group = new Konva.Group({
  clipFunc: function(ctx) { 
    clipSquare(ctx, oX, oY, oW, oH, radius)
    },
  draggable: true
});

layer.add(rect1)
group.add(rect2)
layer.add(group)
stage.draw();
#container {
width: 500px;
height: 300px;
background-color: #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/konva/3.2.5/konva.min.js"></script>

<div id='container'>

</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...