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

房东的猫 提交于 2019-12-31 05:32:29

问题


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


回答1:


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>


来源:https://stackoverflow.com/questions/56028900/how-to-add-corner-radius-on-konva-group-using-clip-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!