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

前端 未结 1 1530
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-27 11:57

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条回答
  •  一整个雨季
    2021-01-27 12:51

    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;
    }
    
    
    
    

    0 讨论(0)
提交回复
热议问题