Skip to content Skip to sidebar Skip to footer

How Can I Rotate Any Shape Or Point On An Html5 Canvas Around An Arbitrary Point?

I have seen a few cases of questions asking how to rotate a shape around a given point and decided to ask this self-answer question myself. So - in relation to HTML5 canvas, or in

Solution 1:

It turns out the answer is pretty simple but involves a bit of math that may put some folks off. I'm using the Konvajs HTML5 canvas library but the code is easily transportable to your own lib. Also, this example is described as rotating a shape, but it's really rotating a point - the origin of the shape - so you could use it for any point-rotation-around-a-point case.

The rotateAroundPoint() function does the work - the rest of the code in the snippet is there to make it a working example.

Lifting this function out we can see that the inputs are the shape - although this could be any object with x, y and rotation properties, the rotation angle in degrees, and the rotation point - again an object with x & y values.

When we rotate around the point we are carrying out the equivalent of a rotation-in-place, followed by a translation (or move). These must be done in this sequence. Also, because of how 2d-drawing works, we have to work out the new position for the move and this depends on the drawing origin of the shape.

The calculation of the new x & y positions requires the use of sine & cosine functions which require radians - not degrees. So we multiply degrees by PI / 180 to get that.

// Rotate a shape around any point.// shape is a Konva shape// angleDegrees is the angle to rotate by, in degrees// point is an object {x: posX, y: posY}functionrotateAroundPoint(shape, angleDegrees, point) {
  let angleRadians = angleDegrees * Math.PI / 180; // sin + cos require radiansconst x =
    point.x +
    (shape.x() - point.x) * Math.cos(angleRadians) -
    (shape.y() - point.y) * Math.sin(angleRadians);
  const y =
    point.y +
    (shape.x() - point.x) * Math.sin(angleRadians) +
    (shape.y() - point.y) * Math.cos(angleRadians);
   
  shape.rotation(shape.rotation() + angleDegrees); // rotate the shape in place
  shape.x(x);  // move the rotated shape in relation to the rotation point.
  shape.y(y);

}

That's it! Have a play with the snippet - best viewed full-screen. Select a shape to rotate, then click the rotate button a few times to watch it spin around its origin (the natural point of rotation if we just change the rotation angle and nothing else). Then click the reset button, and click the canvas to move the blue target somewhere else on the canvas or shape, and rotate some more to see the effect.

There's also a codepen version here.

// Code to illustrate rotation of a shape around any given point. The important functions here is rotateAroundPoint() which does the rotation and movement math ! let 
    angle = 0, // display value of angle
    startPos = {x: 80, y: 45},    
    shapes = [],    // array of shape ghosts / tails
    rotateBy = 20,  // per-step angle of rotation 
    shapeName = $('#shapeName').val(),  // what shape are we drawing
    shape = null,
    ghostLimit = 10,

    // Set up a stage
    stage = newKonva.Stage({
        container: 'container',
        width: window.innerWidth,
        height: window.innerHeight
      }),

  
    // add a layer to draw on
    layer = newKonva.Layer(),
    
    // create the rotation target point cross-hair marker
    lineV = newKonva.Line({points: [0, -20, 0, 20], stroke: 'cyan', strokeWidth: 1}),
    lineH = newKonva.Line({points: [-20, 0,  20, 0], stroke: 'cyan', strokeWidth: 1}),
    circle = newKonva.Circle({x: 0, y: 0, radius: 10, fill: 'transparent', stroke: 'cyan', strokeWidth: 1}),
    cross = newKonva.Group({draggable: true, x: startPos.x, y: startPos.y});

// Add the elements to the cross-hair group
cross.add(lineV, lineH, circle);
layer.add(cross);

// Add the layer to the stage
stage.add(layer);


$('#shapeName').on('change', function(){
  shapeName = $('#shapeName').val();
  shape.destroy();
  shape = null;
  reset();
})


// Draw whatever shape the user selectedfunctiondrawShape(){
  
    // Add a shape to rotateif (shape !== null){
      shape.destroy();
    }
   
    switch (shapeName){
      case"rectangle":
        shape = newKonva.Rect({x: startPos.x, y: startPos.y, width: 120, height: 80, fill: 'magenta', stroke: 'black', strokeWidth: 4});
        break;

      case"hexagon":
        shape = newKonva.RegularPolygon({x: startPos.x, y: startPos.y, sides: 6, radius: 40, fill: 'magenta', stroke: 'black', strokeWidth: 4}); 
        break;
        
      case"ellipse":
        shape = newKonva.Ellipse({x: startPos.x, y: startPos.y, radiusX: 40, radiusY: 20, fill: 'magenta', stroke: 'black', strokeWidth: 4});     
        break;
        
      case"circle":
        shape = newKonva.Ellipse({x: startPos.x, y: startPos.y, radiusX: 40, radiusY: 40, fill: 'magenta', stroke: 'black', strokeWidth: 4});     
        break;

      case"star":
        shape = newKonva.Star({x: startPos.x, y: startPos.y, numPoints: 5, innerRadius: 20, outerRadius: 40, fill: 'magenta', stroke: 'black', strokeWidth: 4});     
        break;        
    };
    layer.add(shape);
    
    cross.moveToTop();

  }



// Reset the shape position etc.functionreset(){

  drawShape();  // draw the current shape// Set to starting position, etc.
  shape.position(startPos)
  cross.position(startPos);
  angle = 0;
  $('#angle').html(angle);
  $('#position').html('(' + shape.x() + ', ' + shape.y() + ')');
  
  clearTails(); // clear the tail shapes
  
  stage.draw();  // refresh / draw the stage.
}




// Click the stage to move the rotation point
stage.on('click', function (e) {
  cross.position(stage.getPointerPosition());
  stage.draw();
});

// Rotate a shape around any point.// shape is a Konva shape// angleRadians is the angle to rotate by, in radians// point is an object {x: posX, y: posY}functionrotateAroundPoint(shape, angleDegrees, point) {
  let angleRadians = angleDegrees * Math.PI / 180; // sin + cos require radiansconst x =
    point.x +
    (shape.x() - point.x) * Math.cos(angleRadians) -
    (shape.y() - point.y) * Math.sin(angleRadians);
  const y =
    point.y +
    (shape.x() - point.x) * Math.sin(angleRadians) +
    (shape.y() - point.y) * Math.cos(angleRadians);
   
  shape.rotation(shape.rotation() + angleDegrees); // rotate the shape in place
  shape.x(x);  // move the rotated shape in relation to the rotation point.
  shape.y(y);
  
  shape.moveToTop(); // 
}



$('#rotate').on('click', function(){
  
  let newShape = shape.clone();
  shapes.push(newShape);
  layer.add(newShape);
  
  // This ghost / tails stuff is just for fun.if (shapes.length >= ghostLimit){
    shapes[0].destroy();   
    shapes = shapes.slice(1);
  }
  for (var i = shapes.length - 1; i >= 0; i--){
    shapes[i].opacity((i + 1) * (1/(shapes.length + 2)))
  };

  // This is the important call ! Cross is the rotation point as illustrated by crosshairs.rotateAroundPoint(shape, rotateBy, {x: cross.x(), y: cross.y()});
  
  cross.moveToTop();
  
  stage.draw();
  
  angle = angle + 10;
  $('#angle').html(angle);
  $('#position').html('(' + Math.round(shape.x() * 10) / 10 + ', ' + Math.round(shape.y() * 10) / 10 + ')');
})



// Function to clear the ghost / tail shapesfunctionclearTails(){

  for (var i = shapes.length - 1; i >= 0; i--){
    shapes[i].destroy();
  };
  shapes = [];
  
}

// User cicks the reset button.
$('#reset').on('click', function(){

  reset();

})

// Force first draw!reset();
body {
  margin: 10;
  padding: 10;
  overflow: hidden;
  background-color: #f0f0f0;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><scriptsrc="https://unpkg.com/konva@^3/konva.min.js"></script><p>1. Click the rotate button to see what happens when rotating around shape origin.</p><p>2. Reset then click stage to move rotation point and click rotate button again - rinse & repeat</p><p><buttonid = 'rotate'>Rotate</button><buttonid = 'reset'>Reset</button><selectid='shapeName'><optionvalue='rectangle'>Rectangle</option><optionvalue='hexagon'>Polygon</option><optionvalue='ellipse' >Ellipse</option><optionvalue='circle' >Circle</option><optionvalue='star'selected='selected'>Star</option></select>
  Angle :    <spanid='angle'>0</span>
Position :   <spanid='position'></span></p><divid="container"></div>

Post a Comment for "How Can I Rotate Any Shape Or Point On An Html5 Canvas Around An Arbitrary Point?"