Rotate icon with SVG using Fabric.js
Example of using fabric.Path to render a "rotate" sign with the correct center pivot, with a configurable size and position.
Uses Fabric.js
HTML
<script src="//rawgithub.com/kangax/fabric.js/master/dist/all.js"></script>
<canvas id="c" width="600" height="600"></canvas>
CSS
canvas {
border-width: 1pz;
border-style: solid;
border-color: #000;
}
JavaScript
this.canvas = new fabric.Canvas('c')
this.canvas.clear();
// Given a radius, calculate the coordinates for the
// middle top and the coordinates of the point on the
// circle which intersects a line from the center of
// the circle at a downward-right 45 degree angle.
function rotatePoints(radius) {
// Get 45 degrees in radians
var angle = Math.PI / 4;
return {
radius: radius,
startPos: {
x: radius,
y: 0
},
endPos: {
x: radius + (radius * Math.cos(angle)),
y: radius + (radius * Math.sin(angle))
}
}
}
// Use the rotatePoints function to do the path for the arc
var pathPts = rotatePoints(30);
// The ratio of the arrow (fabric.Triangle) to the arc radius
var arrowScale = 0.666;
// Pivot position of the rotate 'widget'
var rotatePos = {x: 300, y: 300}
// Build an array which we'll join into the SVG path statement below
var pathSVG = [
'M', pathPts.startPos.x, pathPts.startPos.y,
'A', pathPts.radius, pathPts.radius,
0, 1, 0,
pathPts.endPos.x, pathPts.endPos.y
];
// Create the Path instance using an SVG string generated by
// the rotatePoints function
var path = new fabric.Path(
pathSVG.join(' '), {
fill: '',
stroke: '#35a2da',
// stroke is relative to the radius
strokeWidth: pathPts.radius / 4,
left: rotatePos.x,
top: rotatePos.y,
width: pathPts.radius * 2,
height: pathPts.radius * 2
});
// Position the triangle relative to the start of the arc
var triangle = new fabric.Triangle({
width: pathPts.radius * arrowScale,
height: pathPts.radius * arrowScale,
fill: '#35a2da',
left: rotatePos.x,
top: rotatePos.y - pathPts.radius,
angle: 90
});
// The Group object size is explicitly set based on the arc
// radius. Otherwise, it would default to a size including the
// width of the arc's stroke and the triangle, and would be
// lopsided when rotated.
var rotate = new...