2014-11-14 2 views
0

http://jsfiddle.net/s1n6cssa/12/캔버스 회전이 예상대로 작동하지 않는

HTML

<a href="#" id="rotate">Rotate</a> 
<div id="print-region"> 
    <img class="overlay" src="http://www.itasveer.com/common/images/mobilecover/apple-5_5s.png" /> <span id="uploaded-image-container"></span> 

    <img class="overlay" src="http://www.itasveer.com/common/images/mobilecover/apple-5_5s_white.png" /> 
</div> 

CSS

#myCanvas { 
height: 100%; 
width: 100%; 
background-color: blue; 
} 
#print-region { 
    height: 542px; 
    width: 520px; 
    margin: 0; 
    position: relative; 
    overflow: hidden; 
} 
.overlay { 
    position: absolute; 
    pointer-events: none; 
} 
#rotate { 
    width: 100px; 
    height: 30px; 
} 

내가 표시된 부분의 스냅 샷을하고 싶어

var context; 
var canvas; 
var nHeight; //the new height after resizing 
var nWidth; //the new width after resizing 
var TO_RADIANS = Math.PI/180; 
var imageObj = new Image(); 

//USE ONLY ONE OF THE BELOW IMAGES AT A TIME 

//square image which does not distort after rotation 
imageObj.src = "http://i.stack.imgur.com/hwxO6.png"; 


//rectangular image which distorts after rotation 
<!-- imageObj.src = "http://g-ecx.images-amazon.com/images/G/01/electronics/detail-page/Klipsch-Image-S4-II-Black-Lifestyle.jpg"; --> 


var originalWidth = imageObj.width; 
var originalHeight = imageObj.height; 

$('#myCanvas').remove(); 


//used by context.rotate and updated after every rotation 
$("#uploaded-image-container").attr({ 
    rotation: 0 
}); 

$("#uploaded-image-container").append("<canvas id='myCanvas'></canvas>"); 


$("#uploaded-image-container").css({ 
    "position": "absolute", 
     "height": originalHeight/3, //one-third size of the original height of the uploaded image 
     "width": originalWidth/3, 
     "top": $('#print-region').height()/3, 
     "left": $('#print-region').width()/3 
}); 

canvas = document.getElementById('myCanvas'); 

context = canvas.getContext('2d'); 
nHeight = canvas.height = originalHeight/3; 
nWidth = canvas.width = originalWidth/3; 


imageObj.onload = function() { 
    context.drawImage(imageObj, 0, 0, originalWidth/3, originalHeight/3); 
}; 

$("#uploaded-image-container").draggable({ 
    snap: false, 
    scroll: false, 
    cursor: "move", 
    containment: '#print-region' 
}); 


$("#uploaded-image-container").resizable({ 
    handles: 'nw, ne, sw, se', 
    aspectRatio: true, 
    containment: '#print-region', 

    resize: function (e, ui) { 
     nHeight = ui.size.height; 
     nWidth = ui.size.width; 
    } 
}); 


$("#rotate").click(function() { 
    updateRotation($("#uploaded-image-container")); 
}); 


var imageRotation = 0; // the angle that the image is rotated 
var updateRotation = function (elem) { 
    var angle = parseInt(elem.attr('rotation')); 

//after rotation, the nWidth and nHeight are interchanged hence temp variables 
    var tempHeight, tempWidth; 

    if (angle == 0) { 
     imageRotation = 90; 
     elem.attr('rotation', 90); 
     tempHeight = nWidth; 
     tempWidth = nHeight; 
    } else if (angle == 90) { 
     imageRotation = 180; 
     elem.attr('rotation', 180); 
     tempHeight = nHeight; 
     tempWidth = nWidth; 
    } else if (angle == 180) { 
     imageRotation = 270; 
     elem.attr('rotation', 270); 
     tempHeight = nWidth; 
     tempWidth = nHeight; 
    } else { 
     imageRotation = 0; 
     elem.attr('rotation', 0); 
     tempHeight = nHeight; 
     tempWidth = nWidth; 
    } 

    $("#uploaded-image-container").css({ 
     "height": tempHeight, 
      "width": tempWidth 
    }); 

    canvas.width = tempWidth; 
    canvas.height = tempHeight; 
    context.translate(tempWidth/2, tempHeight/2); 
    context.rotate(imageRotation * TO_RADIANS); 
    context.translate(-tempWidth/2, -tempHeight/2); 
    context.drawImage(imageObj, 0, 0, tempWidth, tempHeight); 
}; 

JAVASCRIPT js의 결과 html2canvas 플러그인을 사용하여 바이올린. 하지만 html2canvas는 CSS3 rotate 속성을 지원하지 않습니다. 그래서 캔버스를 사용하여 이미지를 회전 시켰으며 회전이 html2canvas에 의해 성공적으로 캡쳐되었습니다.

위의 코드에서 정사각형 이미지를 사용하면 완전히 회전하지만 직사각형 이미지를 사용하면 이미지 너비와 높이가 왜곡됩니다.

크기 조정, 끌기 및 회전을 조합하면 이미지가 왜곡되어서는 안됩니다.

무엇이 문제입니까?

답변

0

이미지를 그리거나 크기를 조정할 때 임시 값 (너비와 높이)을 방향으로 사용하기 때문입니다. 방향의 값이 setContainerHeight 및 setContainerWidth에 적용됩니다. 즉, 좌표와 배율과 같은 값을 사용합니다.

네모 난 (너비 = 높이)이므로 첫 번째 이미지가 보이지 않습니다. 따라서 문제는 발생하지 않지만 직사각형은 너비 = 2 * 높이; 따라서 이미지 비율을 사용하십시오. 이

var context; 
    var canvas; 
    var nHeight; 
    var nWidth; 
    var TO_RADIANS = Math.PI/180; 
    var imageObj = new Image(); 
    imageObj.src = "http://g-ecx.images-amazon.com/images/G/01/electronics/detail-page/Klipsch-Image-S4-II-Black-Lifestyle.jpg"; 


    var originalWidth = imageObj.width; 
    var originalHeight = imageObj.height; 

    $('#myCanvas').remove(); 
    $("#uploaded-image-container").attr({ 
     rotation: 0 
    }); 

    $("#uploaded-image-container").append("<canvas id='myCanvas'></canvas>"); 


    $("#uploaded-image-container").css({ 
     "position": "absolute", 
      "height": originalHeight/3, 
      "width": originalWidth/3, 
      "top": $('#print-region').height()/3, 
      "left": $('#print-region').width()/3 
    }); 

    canvas = document.getElementById('myCanvas'); 

    context = canvas.getContext('2d'); 
    nHeight = canvas.height ; 
    nWidth = canvas.width ; 


    imageObj.onload = function() { 
     context.drawImage(imageObj, 0, 0, originalWidth/3, originalHeight/3); 
    }; 

    $("#uploaded-image-container").draggable({ 
     snap: false, 
     scroll: false, 
     cursor: "move", 
     containment: '#print-region' 
    }); 


    $("#uploaded-image-container").resizable({ 
     handles: 'nw, ne, sw, se', 
     aspectRatio: true, 
     containment: '#print-region', 

     resize: function (e, ui) { 
      nHeight = ui.size.height; 
      nWidth = ui.size.width; 
     } 
    }); 


    $("#rotate").click(function() { 
     updateRotation($("#uploaded-image-container")); 
    }); 

var imageRotation = 0; // the angle that the image is rotated 
var updateRotation = function (elem) { 
    var angle = parseInt(elem.attr('rotation')); 
    var ratio = nWidth/nHeight; 
    var customX = nWidth, scaleX = nWidth; 
    var customY = nHeight, scaleY = nHeight; 
    var tempHeight, tempWidth; 
    //the problem is in number 1 and 3 
    if (angle == 0) { //number 1 
     imageRotation = 90; 
     elem.attr('rotation', 90); 
     tempHeight = nWidth; 
     tempWidth = nHeight; customY = ratio*customY; 
    } else if (angle == 90) { //number 2 
     imageRotation = 180; 
     elem.attr('rotation', 180); 
     tempHeight = nHeight; 
     tempWidth = nWidth ; 
    } else if (angle == 180) { 
     imageRotation = 270; 
     elem.attr('rotation', 270); 
     tempHeight = nWidth; 
     tempWidth = nHeight; customY = ratio*customY; 
    } else { // number 4 handle 
     imageRotation = 0; 
     elem.attr('rotation', 0); 
     tempHeight = nHeight; 
     tempWidth = nWidth; 
    } 

    $("#uploaded-image-container").css({ 
     "height": tempHeight, 
     "width": tempWidth 
    }); 

    canvas.width = customX; 
    canvas.height = customY; 
    context.translate(customX/2, customY/2); 
    context.rotate(imageRotation * TO_RADIANS); 
    context.translate(-customX/2, -customY/2);   
    context.drawImage(imageObj, 0, 0, customX, customY); 
}; 
+0

감사합니다. 나는 명성이 15 점이므로 투표를 할 수 없다. 나는 그 명성에 도달 할 때 투표 할 것입니다. :) – user3752017

0

시도해보십시오. http://jsfiddle.net/5hrx77nr/ 피들.

context.drawImage(imageObj, 0, 0, 100, 100 * imageObj.height/imageObj.width) 

기본적으로 html5는 이미지를 캔버스 크기로 수평 확장하므로 수동으로 이미지 크기를 관리해야합니다.

+0

http://jsfiddle.net/5hrx77nr/1/ 내가 당신의 갈래 코드의 첫 번째 이미지를 댓글을 달았 형성 모든 상자에 작동합니다. 다른 변경 사항은 없습니다. 그것은 작동하지 않습니다. – user3752017

0

당신은 무엇을하려고하는지 조금 더 설명해야합니다. 나는 회전이 그렇게 복잡하지 않다고 생각한다.

어쨌든. 33, 34 번 줄에 오류가 있습니다.

어쩌면 당신이 의미하는 것은 더하기 또는 곱셈입니까? 파란색 캔버스가 나타나고 회전하기 때문에 바뀝니다.

nHeight = canvas.height + originalHeight/3; 
    nWidth = canvas.width + originalWidth/3; 
+0

나는 더 많은 설명과 함께 게시물을 편집했다. 파란색은 회전 후 캔버스 영역을 확인하기위한 것입니다. 이미지가 제대로 회전하면 파란색 배경이 보이지 않아야합니다. 코드에 주석을 추가하겠습니다. – user3752017

+0

회전을 클릭하면 그림이있는 다른 캔버스가 90도 회전합니다. ?? 원본 사진이 회전하거나 그대로 머 무르지 않습니까? – vdj4y

+0

다른 플러그인에서 사용할 이미지를 회전시키고 싶을뿐입니다. 단지 1.create canvas; 2.context.drawImage (img.jpg)/* 캔버스에 jpg 삽입 */3.context.rotate(); – vdj4y

관련 문제