【问题标题】:After rotate, draw Image at correct position旋转后,在正确的位置绘制图像
【发布时间】:2016-01-09 00:56:10
【问题描述】:

如您所见,我尝试在画布中旋转图像: https://jsfiddle.net/1a7wpsp8/4/

因为我围绕[0, image_height] 旋转了图像,所以图像信息丢失了。 部分头部丢失,现在画布的高度太小,无法显示整个旋转图像。

要解决这个问题我想我必须将旋转原点向右移动并增加画布高度。

我添加了一个方法来获取围绕原点旋转特定角度的点:

function rotate(x, y, a) {
 var cos = Math.cos,
    sin = Math.sin,

    a = a * Math.PI / 180, 
    xr =  x * cos(a) - y * sin(a);
    yr =  x * sin(a) + y * cos(a);

 return [xr, yr];
}

我尝试计算新的旋转原点,但失败了。

旋转图像的首选方法是什么? 如何在画布上显示完整的图像,没有红色边框? 谢谢 https://jsfiddle.net/1a7wpsp8/4/

【问题讨论】:

  • 但是你没有使用这个rotate()函数。你正在使用ctx.rotate()
  • 只要您用红色填充画布背景,红色三角形将始终是旋转图像的副产品。您是在问如何缩小旋转图像以适应画布元素的原始边界?

标签: javascript jquery html canvas


【解决方案1】:

要旋转图像并对其进行缩放,以使图像的边缘在任何时候都不会在画布边界内,您需要计算从画布中心到角落的距离。

// assuming canvas is the canvas and image is the image.
var dist = Math.sqrt(Math.pow(canvas.width/2,2)+Math.pow(canvas.height/2,2));

现在你需要找到图像中心到其最近边缘的距离;

var imgDist = Math.min(image.width,image.height)/2

所以现在我们有了获取图像在画布中心绘制时始终适合画布的最小比例所需的信息。

var minScale = dist / imgDist;

现在围绕图像的中心旋转、缩放并将其放置在画布的中心

首先计算一个像素的上边缘(X轴)的方向和大小

// ang is the rotation in radians
var dx = Math.cos(ang) * minScale;
var dy = Math.sin(ang) * minScale; 

然后创建转换矩阵,其中前两个数字是 X 轴,后两个数字是 Y 轴,与 X 轴顺时针方向成 90 度,最后两个数字是画布像素坐标的原点,位于画布原点左上角。

// ctx is the canvas 2D context
ctx.setTransform(dx, dy, -dy, dx, canvas.width / 2, canvas.height / 2);

现在绘制偏移一半高度和宽度的图像。

ctx.drawImage(image,-image.width / 2, - image.height / 2);

最后一件事就是恢复默认转换

ctx.setTransform(1,0,0,1,0,0);

你就完成了。

作为一个函数

// ctx is canvas 2D context
// angle is rotation in radians
// image is the image to draw
function drawToFitRotated(ctx, angle, image){
    var dist = Math.sqrt(Math.pow(ctx.canvas.width /2, 2 ) + Math.pow(ctx.canvas.height / 2, 2));
    var imgDist = Math.min(image.width, image.height) / 2;
    var minScale = dist / imgDist;
    var dx = Math.cos(angle) * minScale;
    var dy = Math.sin(angle) * minScale; 
    ctx.setTransform(dx, dy, -dy, dx, ctx.canvas.width / 2, ctx.canvas.height / 2);
    ctx.drawImage(image, -image.width / 2, - image.height / 2);
    ctx.setTransform(1, 0, 0, 1, 0, 0);
}

更新 由于这是一个有趣的问题,我想看看我是否可以弄清楚如何最适合旋转的图像,以确保图像始终填满画布,同时显示尽可能多的图像。解决方案意味着随着图像的旋转,比例会发生变化,并且由于边角会发生变化,所以比例有 4 个点,在这些点上它突然停止收缩并再次开始增长。尽管如此,这对于旋转但需要填充画布的静态图像来说是很好的。

最好的描述方式是用图片 图像是绿色的,画布是红色的。图像的旋转是角度 R 我们需要找到线 C-E 和 C-F 的长度。 Ih 和 Iw 是图像高度和宽度的一半。

从画布中,我们计算出线 C-B 的长度,即画布高度 (ch) 和宽度 (cw) 的一半平方和的平方根。

那么我们需要角度 A,它是 (ch) / 长度线 C-B 的 acos

现在我们有了角度 A,我们可以计算出角度 A1 和 A2。现在我们有了长度 C-B 和角度 A1、A2,我们可以解出 C-E 和 C-F 的直角三角形 C-E-B 和 C-F-B。 即 C-E = 长度 C-B * cos(A1) 和 C-F = 长度 C-B * cos(A2)

然后得到图像高度的比例,即长度 C-E 除 Ih 和 C-E 除 Iw。由于图像方面可能与我们需要适应的矩形不匹配,我们需要保持两个比例的最大值。

所以我们最终得到了一个适合的规模。

还有一个问题。数学适用于 0 -90 度的角度,但其余的则失败。幸运的是,每个象限的问题都是对称的。对于 > 180 的角度,我们镜像并向后旋转 180 度,然后对于角度 > 90

然后它只是创建矩阵和绘制图像的问题。

在演示中,我添加了两个盒子。 red BLUE 是画布轮廓的一半大小的副本,Blue RED 是图像的一半大小。我这样做是为了让您了解为什么图像在旋转时缩放不平滑。

我会为自己保留这个功能,它也很方便。

查看新功能的演示代码。

demo = function(){
    /** fullScreenCanvas.js begin **/
    var canvas = (function(){
        var canvas = document.getElementById("canv");
        if(canvas !== null){
            document.body.removeChild(canvas);
        }
        // creates a blank image with 2d context
        canvas = document.createElement("canvas"); 
        canvas.id = "canv";    
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight; 
        canvas.style.position = "absolute";
        canvas.style.top = "0px";
        canvas.style.left = "0px";
        canvas.style.zIndex = 1000;
        canvas.ctx = canvas.getContext("2d"); 
        document.body.appendChild(canvas);
        return canvas;
    })();
    var ctx = canvas.ctx;
    var image = new Image();
    image.src = "http://i.imgur.com/gwlPu.jpg";

    var w = canvas.width;
    var h = canvas.height;
    var cw = w / 2;  // half canvas width and height
    var ch = h / 2;
    // Refer to diagram in answer 
    function drawBestFit(ctx, angle, image){
        var iw = image.width / 2;  // half image width and height
        var ih = image.height / 2;
        // get the length C-B
        var dist = Math.sqrt(Math.pow(cw,2) + Math.pow(ch,2));
        // get the angle A
        var diagAngle = Math.asin(ch/dist);

        // Do the symmetry on the angle
        a1 = ((angle % (Math.PI *2))+ Math.PI*4) % (Math.PI * 2);
        if(a1 > Math.PI){
            a1 -= Math.PI;
        }
        if(a1 > Math.PI/2 && a1 <= Math.PI){
            a1 = (Math.PI/2) - (a1-(Math.PI/2));
        }
        // get angles A1, A2
        var ang1 = Math.PI/2 - diagAngle - Math.abs(a1);
        var ang2 = Math.abs(diagAngle - Math.abs(a1));
        // get lenghts C-E and C-F
        var dist1 = Math.cos(ang1) * dist;
        var dist2 = Math.cos(ang2) * dist;
        // get the max scale
        var scale = Math.max(dist2/(iw),dist1/(ih));
        // create the transform
        var dx = Math.cos(angle) * scale;
        var dy = Math.sin(angle) * scale; 
        ctx.setTransform(dx, dy, -dy, dx, cw, ch);
        ctx.drawImage(image, -iw, - ih);


        // draw outline of image half size
        ctx.strokeStyle = "red";
        ctx.lineWidth = 2 * (1/scale);
        ctx.strokeRect(-iw / 2, -ih / 2, iw, ih) 

        // reset the transform
        ctx.setTransform(1, 0, 0, 1, 0, 0);

        // draw outline of canvas half size
        ctx.strokeStyle = "blue";
        ctx.lineWidth = 2;
        ctx.strokeRect(cw - cw / 2, ch - ch / 2, cw, ch) 

    }

    // Old function
    function drawToFitRotated(ctx, angle, image){
        var dist = Math.sqrt(Math.pow(cw,2) + Math.pow(ch,2));
        var imgDist = Math.min(image.width, image.height) / 2;
        var minScale = dist / imgDist;

        var dx = Math.cos(angle) * minScale;
        var dy = Math.sin(angle) * minScale; 
        ctx.setTransform(dx, dy, -dy, dx, cw, ch);
        ctx.drawImage(image, -image.width / 2, - image.height / 2);
        ctx.setTransform(1, 0, 0, 1, 0, 0);
    }      

    var angle = 0;
    function update(){  // animate the image
        if(image.complete){
            angle += 0.01;
            drawBestFit(ctx,angle,image);
        }
        
        // animate until resize then stop remove canvas and flag that it has stopped
        if(!STOP){
            requestAnimationFrame(update);
        }else{
           STOP = false;
           var canv = document.getElementById("canv");
           if(canv !== null){
              document.body.removeChild(canv);
           }
            
        }
        
    }
    update();
}
/** FrameUpdate.js end **/
var STOP = false;  // flag to tell demo app to stop 
// resize Tell demo to stop then wait for it to stop and start it again
function resizeEvent(){
    var waitForStopped = function(){
        if(!STOP){  // wait for stop to return to false
            demo();
            return;
        }
        setTimeout(waitForStopped,200);
    }
    STOP = true;
    setTimeout(waitForStopped,100);
}
// if resize stop demo and restart
window.addEventListener("resize",resizeEvent);
 // start demo
demo();

【讨论】:

【解决方案2】:

这是一个用于图像旋转的代码:) http://jsfiddle.net/6ZsCz/1911/

HTML:

canvas id="canvas" width=300 height=300></canvas><br>
<button id="clockwise">Rotate right</button>
<button id="counterclockwise">Rotate left</button>

JS:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var width=0;
var height=0;
var diagonal = 0;
var angleInDegrees=0;
var image=document.createElement("img");
image.onload=function(){
    width = image.naturalWidth;
  height = image.naturalHeight;
 diagonal=Math.sqrt(Math.pow(width,2)+Math.pow(height,2));
   ctx.canvas.height = diagonal;
  ctx.canvas.width = diagonal;
  ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.save();
    ctx.translate(diagonal/2,diagonal/2);
    ctx.rotate(0);
    ctx.drawImage(image,-width/2,-height/2);
    ctx.restore();
}
image.src="http://i.imgur.com/gwlPu.jpg";

$("#clockwise").click(function(){ 
    angleInDegrees+=45;
    drawRotated(angleInDegrees);
});

$("#counterclockwise").click(function(){ 
    angleInDegrees-=45;
    drawRotated(angleInDegrees);
});

function drawRotated(degrees){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.save();
    ctx.translate(diagonal/2,diagonal/2);
    ctx.rotate(degrees*Math.PI/180);
    ctx.drawImage(image,-width/2,-height/2);
    ctx.restore();
}

CSS(画布背景):

canvas{border:1px solid red;
background:red;border-radius:50%} // to see exectly centered :)

【讨论】:

    【解决方案3】:

    旋转图像的首选方法是什么?

    将上下文坐标平移到中心,旋转,然后使用负偏移量绘制,

    ctx.save();
    ctx.translate(width/2, height/2);
    ctx.rotate(-40*Math.PI/180);
    ctx.drawImage(img, -width/2, -height/2);
    ctx.restore();
    

    你将如何在画布上显示完整的图像,没有红色边框?

    要使图像以任意旋转方式适应画布,您必须同时设置宽度和高度(至少)C 其中C=sqrt(width^2 + height^2)。双向翻译为C/2

    【讨论】:

    • 我开始认为提问者希望缩小图像以适应原始画布的大小 - 请参阅提问者对 John Bupit 的评论中的线索。但我不太确定... :-//
    • @markE 哦,你可能是对的。我认为 Blindman67 解决了这个问题。
    【解决方案4】:

    要围绕中心旋转,您可以先将其平移到中心点,然后旋转,然后再平移回来。像这样的:

    ctx.translate(width/2, height/2);
    ctx.rotate(-40*Math.PI/180);
    ctx.translate(-width/2, -height/2);
    

    // Grab the Canvas and Drawing Context
    var canvas = $('#c');
    var ctx = canvas.get(0).getContext('2d');
    
    //rotate point x,y around origin with angle a, get back new point 
    function rotate(x, y, a) {
      var cos = Math.cos,
        sin = Math.sin,
    
        a = a * Math.PI / 180,
        xr = x * cos(a) - y * sin(a);
      yr = x * sin(a) + y * cos(a);
    
      return [xr, yr];
    }
    
    // Create an image element
    var img = document.createElement('IMG');
    
    // When the image is loaded, draw it
    img.onload = function() {
      var width = img.naturalWidth;
      var height = img.naturalHeight;
    
      canvas.attr('width', width);
      canvas.attr('height', height);
    
      //only to show that borders of canvas
      ctx.rect(0, 0, width, height);
      ctx.fillStyle = "red";
      ctx.fill();
    
      ctx.save();
      ctx.translate(width / 2, height / 2);
      ctx.rotate(-40 * Math.PI / 180); //comment this line out to see orign image
      ctx.translate(-width / 2, -height / 2);
      ctx.drawImage(img, 0, 0);
      ctx.restore();
    
    }
    
    // Specify the src to load the image
    img.src = "http://i.imgur.com/gwlPu.jpg";
    body {
      background: #CEF;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <canvas id="c"></canvas>

    【讨论】:

    • 感谢您的回答。但我正在寻找一种解决方案,其中图像的边界点位于画布的边界上。如您所见,画布必须放大。
    【解决方案5】:

    将旋转中心移动到 Canvas 的近似中心: 请参阅源代码 http://wisephoenix.org/html5/Rotation.htm 这是用html5和javascript编写的。

    【讨论】:

    • 您应该在答案中发布相关代码,而不是仅发布链接。
    猜你喜欢
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多