javascript - Rotate and image canvas by user defined angle -
i want rotate image user defined angle determined input slider ranges -90deg 90deg. requirement straighten image on canvas.
this have tried using angularjs
my input slider , html :
straighten: <input type="range" id="rotateimage" value="0" min="-90" max="90" step="1" ng-model="rotateangle"/> <div id="imagecanvas"> <canvas id="canvas"></canvas> </div>
my controller:
$scope.$watch('rotateangle', function(newval, oldval) { if (newval) { rotate(newval) } }) function rotate(rotangle) { console.log('rotate angle>> ', rotangle); var imagecanvas = document.getelementbyid("canvas"), context = canvas.getcontext("2d"); var gridwidth = imagecanvas.width, gridheight = imagecanvas.height; var deg = math.pi / 180; context.translate(gridwidth / 2, gridheight / 2); context.rotate(rotangle * deg); }
also drawing grid on top of canvas reference
$scope.straighten = function() { var imagecanvas = document.getelementbyid("canvas"), gridwidth = imagecanvas.width, canvaswidth = gridwidth, gridheight = imagecanvas.height, canvasheight = gridheight, gridpadding = 1; var gridcanvas = $('<canvas id=gridlayer></canvas>').attr({ width: canvaswidth, height: canvasheight }).appendto('#imagecanvas'); var context = gridcanvas.get(0).getcontext("2d"); drawgridboard(gridwidth, gridheight, gridpadding, context); } function drawgridboard(gridwidth, gridheight, gridpadding, context) { (var x = 0; x <= gridwidth; x += 40) { context.moveto(0.5 + x + gridpadding, gridpadding); context.lineto(0.5 + x + gridpadding, gridheight + gridpadding); } (var x = 0; x <= gridheight; x += 40) { context.moveto(gridpadding, 0.5 + x + gridpadding); context.lineto(gridwidth + gridpadding, 0.5 + x + gridpadding); } context.strokestyle = "blue"; context.setlinedash([15, 5]); context.stroke();
}
i able angle image has rotated image not getting roatated. please
i've been working on canvas since couple of weeks. i'm updating rotate function. maybe should have wait until image loaded before draw it. please post below code
function rotate(rotangle) { console.log('rotate angle>> ', rotangle); var canvas= document.getelementbyid("canvas"), context = canvas.getcontext("2d"); context.clearrect(0, 0, canvas.width, canvas.height); //clear canvas first var logoimg = new image(); // create instance of image class logoimg.src = item.image; // tell image's relative url var gridwidth = canvas.width, var gridheight = canvas.height; var deg = math.pi / 180; logoimg.onload = function () { context.save(); context.translate(gridwidth / 2, gridheight / 2); context.rotate(rotangle * math.pi / 180); context.drawimage(logoimg, -(gridwidth / 2), -(gridheight / 2)); context.restore(); }; }
above code worked me.
Comments
Post a Comment