图像旋转 - 根据图像高度和宽度调整画布大小 [英] Image rotate - resize canvas based on image height and width

查看:455
本文介绍了图像旋转 - 根据图像高度和宽度调整画布大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想旋转图像,但根据图像的宽度和高度调整画布大小。请在js小提琴中查看我的代码


I want to rotate image but resize the canvas based on image's width and height. please see my code in js fiddle "http://jsfiddle.net/6ZsCz/1123/". I am actually rotating an image based on canvas but my canvas has fixed height and width so the image is just rotating inside. all i want something like this. Please check my attached screenshot. green border is a canvas so if i rotate 90 degree then canvas should expand the height and show the entire image.

Can you please help?

HTML

<canvas id="canvas" ></canvas><br>
<button id="clockwise">Rotate right</button>

Javascript

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var degrees=0;
var image=document.createElement("img");
image.onload=function(){
    ctx.drawImage(image,0,0,image.width,image.height);
}
image.src="http://www.ajaxblender.com/article-sources/images/plane-1.jpg";
$("#clockwise").click(function(){
   degrees+=90
   ctx.clearRect(0,0,canvas.width,canvas.height);
   ctx.save();
   ctx.translate(image.width/2,image.height/2);
   ctx.rotate(degrees*Math.PI/180);
   ctx.drawImage(image,0,0,image.width,image.height,-image.width/2,-image.height   /2,image.width,image.height);
   ctx.restore();
});

解决方案

First initialize the canvas size when the image has loaded:

image.onload=function(){
    canvas.width = image.width;
    canvas.height = image.height;    
    ctx.drawImage(image,0,0);
}

Now you can use the angles as basis for the canvas size. If 0 or 180 degrees then use the same size as image, if not swap the dimensions:

 if (degrees >= 360) degrees = 0;

 if (degrees === 0 || degrees === 180) {
     canvas.width = image.width;
     canvas.height = image.height;
 }
 else {
     // swap
     canvas.width = image.height;
     canvas.height = image.width;
 }

There is no need to clear the canvas as changing the size will clear it (otherwise it would only be needed if the image contained a transparency channel).

You also want to rotate the image around the center of canvas (not a big issue here though).

Modified fiddle

这篇关于图像旋转 - 根据图像高度和宽度调整画布大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆