javascript - Rotate canvas 90 degrees clockwise and update width height -
say have canvas:
<canvas id="one" width="100" height="200"></canvas> and on button click canvas gets rotated 90 degrees clockwise (around center) , dimensions of canvas updated, in sense looks afterwards:
<canvas id="one" width="200" height="100"></canvas> note id of canvas same.
imagine rotating image clockwise without being cropped or being padded.
any suggestions before long way of creating new canvas , rotating , copying pixel pixel?
update sample code suggestion comments still not working:
function imagerotatecw90(){ var canvas = document.getelementbyid("one"); var context = canvas.getcontext("2d"); var cw=canvas.width; var ch=canvas.height; var myimagedata = context.getimagedata(0,0, cw,ch); context.save(); context.translate(cw / 2, ch / 2); context.rotate(math.pi/2); context.putimagedata(myimagedata, 0, 0); context.restore(); canvas.width=ch; canvas.height=cw; }
look @ demo.
to achieve results seen in demo, made use of canvas.todataurl cache canvas image, reset canvas new dimensions, translate , rotate context , draw cached image modified canvas.
that way rotate canvas without need redraw again. because anti-aliasing methods used browser, each time operation done you'll notice blurriness in result. if don't behavior solution figure out draw again, more difficult track.
here follows code:
var canvas = document.getelementbyid("one"); var context = canvas.getcontext("2d"); var cw = canvas.width; var ch = canvas.height; // sample graphic context.beginpath(); context.rect(10, 10, 20, 50); context.fillstyle = 'yellow'; context.fill(); context.linewidth = 7; context.strokestyle = 'black'; context.stroke(); // create button var button = document.getelementbyid("rotate"); button.onclick = function () { // rotate canvas 90 degrees each time button pressed rotate(); } var myimagedata, rotating = false; var rotate = function () { if (!rotating) { rotating = true; // store current data image myimagedata = new image(); myimagedata.src = canvas.todataurl(); myimagedata.onload = function () { // reset canvas new dimensions canvas.width = ch; canvas.height = cw; cw = canvas.width; ch = canvas.height; context.save(); // translate , rotate context.translate(cw, ch / cw); context.rotate(math.pi / 2); // draw previows image, rotated context.drawimage(myimagedata, 0, 0); context.restore(); // clear temporary image myimagedata = null; rotating = false; } } }
Comments
Post a Comment