【问题标题】:Having some problems rotating an image inside a canvas在画布内旋转图像时遇到一些问题
【发布时间】:2014-02-17 16:27:13
【问题描述】:

问题: 当我旋转我添加的图像时,图像不会像我想要的那样居中。我在画布内的图片上方不断出现白色区域。

尝试使用 16:9 比例的图像,旋转后您会看到我的问题。这将用于移动设备,因此图片的宽度最大为 640。

Here is a fiddle 当前代码:

HTML:

<div id="files">
    <input type="file" id="imageLoader" name="imageLoader" />
</div>
<canvas id="imageCanvas"></canvas>
<canvas id="preview"></canvas>
        <input type="button" id="saveButton" value="Save" />
<div id="rotate">
        <button type="button" id="rotateLeft">Rotate -90°</button>
        <button type="button" id="rotateRight">Rotate 90°</button>
    </div>

JS:

 var imageLoader = document.getElementById('imageLoader');
    imageLoader.addEventListener('change', handleImage, false);
    var image = "";
    var canvas = document.getElementById('imageCanvas');
    var ctx = canvas.getContext("2d");
    var fileName = "";
    var angleInDegrees = 0;
    function handleImage(e) {
        var reader = new FileReader();
        reader.onload = function(event) {
            var img = new Image();
            img.onload = function() {
                canvas.width = img.width;
                canvas.height = img.height;
                ctx.drawImage(img, 0,0);
                fileName = img.name;
                image = img;
            };
            img.src = event.target.result;
        };
        reader.readAsDataURL(e.target.files[0]);
    }

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

    $("#rotateRight").click(function () {
        angleInDegrees += 90;
        drawRotated(angleInDegrees);
    });

    $("#rotateLeft").click(function () {
        angleInDegrees -= 90;
        drawRotated(angleInDegrees);
    });

jsfiddle.net/dJ5BH

这是我的新小提琴 :) 如果我希望它的最大宽度为 640 怎么办?

【问题讨论】:

    标签: javascript html canvas html5-canvas


    【解决方案1】:

    您的 drawImage 中有错字:

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

    除非您的图像始终是方形的,否则您必须调整画布大小以适应旋转后的图像。

    如何调整画布大小的演示:http://jsfiddle.net/m1erickson/3E99A/

    如果您不想更改画布大小,您的图像将被剪裁。另外,如果图像是横向的,你必须在drawimage中翻转宽度/高度:

    // flip width/height when the image is in landscape orientation
    
    ctx.drawImage(image, -image.height/2, -image.width/2);
    

    如何调整画布大小的代码:

    <!doctype html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
        <style>
            #canvas{
              border: 1px solid green;
            }
        </style>
        <script>
        $(function(){
             var canvas=document.getElementById("canvas");
             var ctx=canvas.getContext("2d");
             var imgWidth=200;
             var imgHeight=300;
             var size={width:imgWidth, height:imgHeight};
             var rotation=0;
             var deg2Rad=Math.PI/180;
             var count1=0;
             var count2=0;
    
              var img=new Image();
              img.onload=function(){
                  imgWidth=img.width;
                  imgHeight=img.height;
                  size={width:imgWidth, height:imgHeight};
                  draw();
              }
              img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/card.png";
    
          function draw(){
             canvas.width=size.width;
             canvas.height=size.height; 
    
             // calculate the centerpoint of the canvas
             var cx=canvas.width/2;
             var cy=canvas.height/2;
             var info=document.getElementById("info");
             info.innerHTML="canvas size: "+(count1++)+": "+cx+" / "+cy;
    
             // draw the rect in the center of the newly sized canvas
             ctx.clearRect(0,0,canvas.width,canvas.height);
             ctx.fillStyle="rgba(216,216,150,1.0)";
             ctx.translate(cx,cy);
             ctx.rotate(rotation * deg2Rad);
             ctx.drawImage(img,-imgWidth/2,-imgHeight/2);
          }
    
          document.getElementById("rotate").addEventListener("click", resizeClicked, false);
    
          function resizeClicked(e){
            rotation+=30;
            newSize(imgWidth,imgHeight,rotation);
            draw();
          }
    
          function newSize(w,h,a){
            var rads=a*Math.PI/180;
            var c = Math.abs(Math.cos(rads));
            var s = Math.abs(Math.sin(rads));
            size.width = h * s + w * c;
            size.height = h * c + w * s ;
          }
    
        });  // end onload
        </script>
    </head>
    <body>
        <button id="rotate">Rotate with resize</button>
        <p id=info></p>
        <canvas id="canvas" width=400 height=400></canvas>
    </body>
    </html>
    

    【讨论】:

    • jsfiddle.net/dJ5BH 这是我的新小提琴 :) 如果我希望它的最大宽度为 640 怎么办?
    • 您可以使用 ctx.scale 缩小任何图像以适合您所需的最大宽度(640px 宽度)。这是一个示例小提琴:jsfiddle.net/m1erickson/pYqTg
    • 谢谢! :) 你在哪里找到这些小提琴?!
    • 不客气。随着时间的推移,我自己创造了许多小提琴,并保存了一批最有用的。
    • 顺便说一句,我正在与这种缩放作斗争。保存时可以缩放图像吗?当我这样做时,它似乎没有保持旋转
    【解决方案2】:

    尝试更改此行:

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

    到:

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

    否则宽度将作为两个轴旋转的基础。

    另请参阅此答案,了解基于旋转将画布旋转并适合图像的一种方法:
    Rotate original Image with jQuery or JavaScript

    【讨论】:

    • jsfiddle.net/dJ5BH 这是我的新小提琴 :) 如果我希望它的最大宽度为 640 怎么办?
    猜你喜欢
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 2021-09-27
    • 2016-03-13
    相关资源
    最近更新 更多