【问题标题】:Image rotate - resize canvas based on image height and width图像旋转 - 根据图像高度和宽度调整画布大小
【发布时间】:2023-03-22 15:30:01
【问题描述】:

我想旋转图像,但根据图像的宽度和高度调整画布的大小。请在JSFiddle 中查看我的代码。我实际上是在基于画布旋转图像,但我的画布具有固定的高度和宽度,因此图像只是在内部旋转。我只想要这样的东西。请检查我随附的屏幕截图。绿色边框是画布,所以如果我旋转 90 度,那么画布应该扩大高度并显示整个图像。

你能帮忙吗?

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();
});

【问题讨论】:

    标签: javascript jquery html5-canvas image-rotation


    【解决方案1】:

    图片加载完毕后首先初始化画布大小:

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

    现在您可以使用角度作为画布大小的基础。如果是 0 或 180 度,则使用与图像相同的尺寸,如果不交换尺寸:

     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;
     }
    

    不需要清除画布,因为更改大小会清除它(否则只有在图像包含透明通道时才需要它)。

    您还想围绕 canvas 的中心旋转图像(不过这里不是大问题)。

    Modified fiddle

    【讨论】:

    • 非常感谢您的快速帮助。还有一个问题。如果我使用 Jquery UI 调整图像大小,那么通常 Jquery UI 在图像上添加样式 =“宽度,高度”,然后如果我旋转图像,那么它只是根据图像原始尺寸而不是调整后图像的尺寸来旋转它。请查看我的 updated JS fiddle。如果我调整图像大小然后旋转图像然后它只是根据调整后的尺寸旋转,是否有可能?
    • @mak 我在这里更新了小提琴。向 html 图像添加一个 id,从中读取 w/h,将其设置在画布上并将其与 drawImage 一起使用,您应该没问题:jsfiddle.net/epistemex/bfwdqgm3 如果仍然不清楚,请打开一个新问题。希望这会有所帮助!
    猜你喜欢
    • 1970-01-01
    • 2017-12-08
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 2014-04-04
    相关资源
    最近更新 更多