After the element is rotated or scaled by transformer, the element cannot be rotated around the center manually

Viewed 24

There is an element in the canvas. Each time I click the button, I want it to rotate 90 degrees around its center point. So when I judge that the origin of this element is not at the center point, I will manually specify its origin to the center point. When I do not use the transformer to rotate or scale it, it works well and can rotate around the center point.However, when I rotate or scale this element through transformer, and then click the button to rotate it, its position is offset, and it can rotate around the center point if I continue to click it. I want it to always rotate 90 degrees around the center point,But I don't know how to solve it. The code is as follows

<button @click="rotate">rotate</button>

let stage = new Konva.Stage({
    container: container,
    width: 800,
    height: 800,
});

let layer = new Konva.Layer();
stage.add(layer);

let rect = new Konva.Rect({
    x:50,
    y:50,
    width: 200,
    height: 150
});
layer.add(rect);

let transformer = new Konva.Transformer({
    rotationSnaps: [0, 90, 180, 270],
    nodes:[rect]
});
layer.add(transformer);

function rotate(){
    if(!rect.attrs.offsetX){
        rect.setAttrs({
            offsetX:rect.attrs.width/2,
            offsetY:rect.attrs.height/2,
            x:rect.attrs.x + rect.attrs.width/2,
            y:rect.attrs.y + rect.attrs.height/2
        })
    }
    rect.rotate(90);
}
1 Answers

            let stage = new Konva.Stage({
                container: container,
                width: 400,
                height: 400,
            })

            let layer = new Konva.Layer()
            stage.add(layer)

            let rect = new Konva.Rect({
                x: 150,
                y: 150,
                width: 200,
                height: 150,
                fill: "red",

                //set offset
                offsetX: 200 / 2,
                offsetY: 150 / 2,
                
            })

            layer.add(rect)

            let transformer = new Konva.Transformer({
                rotationSnaps: [0, 90, 180, 270],
                nodes: [rect],
            })
            layer.add(transformer)

            function rotate() {
                rect.rotate(10)
            }
<script src="https://unpkg.com/konva@8.3.10/konva.min.js"></script>
<button onclick="rotate()">rotate</button>
<div id="container"></div>

Related