在画布内旋转图像时遇到一些问题 [英] Having some problems rotating an image inside a canvas

查看:92
本文介绍了在画布内旋转图像时遇到一些问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:
当我旋转添加的图像时,图像不会像我希望的那样居中。我一直在画布上方的图片上方留下一个白色区域。



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



这是一个小提琴
当前代码:



HTML:

 < div id =files> 
< input type =fileid =imageLoadername =imageLoader/>
< / div>
< canvas id =imageCanvas>< / canvas>
< canvas id =preview>< / canvas>
< input type =buttonid =saveButtonvalue =Save/>
< div id =rotate>
< button type =buttonid =rotateLeft>旋转-90°< / button>
< button type =buttonid =rotateRight>旋转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;
函数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]);
}

函数drawRotated(度){
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宽度怎么办?

解决方案

你的drawImage中有一个拼写错误:

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

除非您的图像始终为方形,否则您必须调整画布大小以允许旋转的图像适合。 / p>

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



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

  //翻转宽度/高度当图像处于横向时

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

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

 <!doctype html> 
< html>
< head>
< link rel =stylesheettype =text / cssmedia =allhref =css / reset.css/> < ;! - reset css - >
< script type =text / javascriptsrc =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;

//计算画布的中心点
var cx = canvas.width / 2;
var cy = canvas.height / 2;
var info = document.getElementById(info);
info.innerHTML =canvas size:+(count1 ++)+:+ cx +/+ cy;

//在新尺寸画布的中心绘制矩形
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);

函数resizeClicked(e){
rotation + = 30;
newSize(imgWidth,imgHeight,rotation);
draw();
}

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

}); //结束onload
< / script>
< / head>
< body>
< button id =rotate>使用调整大小旋转< / button>
< p id = info>< / p>
< canvas id =canvaswidth = 400 height = 400>< / canvas>
< / body>
< / html>


The problem: When i rotate my added image, the image does not center as i would like it to. I keep getting a white area above my picture inside the canvas.

Try with a 16:9 ratio image, and you'll see my problem after a rotate. This will be used for mobile, so the width of the picture could be max 640.

Here is a fiddle Current code:

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

Here is my new fiddle :) What if i want it to be max 640 width?

解决方案

You have a typo in your drawImage:

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

Unless your image is always square, you must resize the canvas to allow the rotated image to fit.

Demo on how to resize the canvas: http://jsfiddle.net/m1erickson/3E99A/

If you don't want to change the canvas size, you're image will be clipped. Also, if the image is in landscape orientation, you must flip the width/height in drawimage:

// flip width/height when the image is in landscape orientation

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

Code on how to resize the canvas:

<!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>

这篇关于在画布内旋转图像时遇到一些问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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