Reputation: 13
Here's a jsfiddle i'm working on.
The jsfiddle rotates an image upon button click by 90 degrees in clockwise or anti-clockwise direction. The rotated image is displayed outside the parent div when rotated. The image may be of any height and width.
How can the rotation be modified to display the image within its parent div maintaining its aspect ratio?
var app = angular.module('rotationApp', []);
app.controller('rotationCtrl', ['$scope',
function($scope) {
$scope.angle = 0;
$scope.rotate = function(angle) {
$scope.angle += angle;
if (($scope.angle === 360)) {
$scope.angle = 0;
}
if ($scope.angle < 0) {
$scope.angle += 360;
}
}
}
]);
app.directive('rotate', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.$watch(attrs.degrees, function(rotateDegrees) {
var r = 'rotate(' + rotateDegrees + 'deg)';
element.css({
'-moz-transform': r,
'-webkit-transform': r,
'-o-transform': r,
'-ms-transform': r,
transform: r
});
});
}
}
});
img {
border: green solid 1px;
}
.container {
margin-top: 100px;
}
.img-holder {
border: red solid 1px;
height: 500px;
width: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app='rotationApp' ng-controller="rotationCtrl">
<div class="container">
<div class="row">
<div class="col-md-6 img-holder">
<img rotate degrees='angle' class="img-responsive" src="http://vignette1.wikia.nocookie.net/uncyclopedia/images/3/3a/Pac_man_pie_chart.jpg/revision/latest?cb=20100508212204">
</div>
<div class="col-md-6">
<button type="button" class="btn btn-lg btn-primary" ng-click="rotate(-90)">
rotate left
</button>
<button type="button" class="btn btn-lg btn-primary" ng-click="rotate(90)">
rotate right
</button>
</div>
</div>
</div>
</div>
Upvotes: 0
Views: 3577
Reputation: 8537
You can add a CSS margin-top
property to do this like this :
var r = 'rotate(' + rotateDegrees + 'deg)';
element.css({
'-moz-transform': r,
'-webkit-transform': r,
'-o-transform': r,
'-ms-transform': r,
transform: r,
'margin-top' : '100px'
});
And if you want to keep the image stick to the top when it is not rotate, you can add this condition :
if(r == "rotate(0deg)" || r == "rotate(180deg)"){
element.css('margin-top',0);
}
Note : If you remove that last condition, it is perfectly centered to the border.
Upvotes: 1