Skip to content Skip to sidebar Skip to footer

Knovajs / HTML5 Canvas - Rotation Origin

I have successfully created a button which rotates an image either clockwise or C-Clockwise. However, this button can only be used once. i.e. if i press CW i cannot then use CCW to

Solution 1:

rotation method will set the current angle of a shape. if you need to rotate more you can use this:

var oldRotation = node.rotation();
node.rotation(oldRotation + 90);

or just:

node.rotate(90);

Solution 2:

Based on @lavrton's answer, here is a working snippet. I guess you need to pay attention to the rotation point - it was easy for me as I used a wedge. See the brief code in the button click events for illustration on what to do.

// add a stage
var s = new Konva.Stage({
  container: 'container',
  width: 800,
  height: 200
});

// add a layer        
var l = new Konva.Layer();
s.add(l);

    
// Add a green rect to the LAYER just to show boundary of the stage.
var green = new Konva.Rect({stroke: 'lime', width: 799, height: 199, x: 0, y: 0});
l.add(green);

// add a circle to contain the wedge
var circle = new Konva.Circle({
      x: s.getWidth() / 2,
      y: s.getHeight() / 2,
      radius: 70,
      fill: 'red',
      stroke: 'black',
      strokeWidth: 4
    });
l.add(circle);

// add the wedge - used as our rotation example
var w = new Konva.Wedge({
      x: s.getWidth() / 2,
      y: s.getHeight() / 2,
      radius: 70,
      angle: 60,
      fill: 'lime',
      stroke: 'black',
      strokeWidth: 4,
      rotation: -120
    });
l.add(w);

l.draw(); // redraw the layer it all sits on.

// wire up the buttons
var oldAngle = 0;
$( document ).ready(function() {
$('#plus90').on('click', function(e){
  oldAngle = w.rotation();
  w.rotate(90);
  $('#info').html('Rotation is ' + oldAngle + ' + 90 = ' + w.rotation())
  l.draw();
})

$('#minus90').on('click', function(e){
  oldAngle = w.rotation();
  w.rotate(-90);
  $('#info').html('Rotation is ' + oldAngle + ' - 90 = ' + w.rotation())
  l.draw();
})

  $('#info').html('Initial rotation = ' + w.rotation())

});
#container {
  border: 1px solid #ccc;
}
#info {
height: 20px;
border-bottom: 1px solid #ccc;
}
#hint {
font-style: italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/konvajs/konva/1.6.3/konva.min.js"></script>


<body>
<div id='hint'>Hint: green is stage, red circle is static, lime wedge rotates.Click the buttons!<br/>
Note the initial rotation set on the creation of the wedge.
</div>

<div id='info'>Info:</div>
<div id='ctrls'>
<button id='minus90'>Rotate -90 degrees</button>
<button id='plus90'>Rotate +90 degrees</button>
</div>


  <div id="container"></div>
</body>

Post a Comment for "Knovajs / HTML5 Canvas - Rotation Origin"