2013-10-29 3 views
0

캔버스에서 이미지가 위에서 아래로 이동하는 기본 HTML5 이미지 슬라이더를 만들었습니다. 모든 이미지를 5도 각도로 회전시키고 싶습니다. 그것을 시도했을 때 캔버스에 약간의 왜곡이 있고 이미지가 제대로 회전되지 않은 것 같습니다.캔버스 이미지 회전 문제

나는 아래의 게시물에서 언급 한 회전 방법을 시도했습니다 바이올린

How do I rotate a single object on an html 5 canvas?

- http://jsfiddle.net/DS2Sb/

코드 여기

this.createImage = function (image, width, height) { 

    var fbWallImageCanvas = document.createElement('canvas'); 
    var fbWallImageCanvasContext = fbWallImageCanvas.getContext('2d'); 
    fbWallImageCanvas.width = width; 
    fbWallImageCanvas.height = height; 

    fbWallImageCanvasContext.save(); 
    fbWallImageCanvasContext.globalAlpha = 0.7; 
    this.rotateImage(image, 0, 0, width, height, 5, fbWallImageCanvasContext); 
    fbWallImageCanvasContext.drawImage(image, width, height); 
    fbWallImageCanvasContext.restore(); 
    return fbWallImageCanvas; 
}; 

this.rotateImage = function (image, x, y, width, height, angle, context) { 

    var radian = angle * Math.PI/180; 
    context.translate(x + width/2, y + height/2); 
    context.rotate(radian); 
    context.drawImage(image, width/2 * (-1), height/2 * (-1), width, height); 
    context.rotate(radian * (-1)); 
    context.translate((x + width/2) * (-1), (y + height/2) * (-1)); 

}; 
+0

코드는 오프 스크린 캔버스에 두 번 이미지를 그릴 것입니다 : 하나는 회전, 하나는 회전하지 않습니다. 코드에서 원하는 것입니까? – markE

답변

1

표시되는 왜곡이 회전 된 이미지는 더 큰 캔버스에 맞는 때문이다 : 여기 https://bitbucket.org/Garlov/html5-sidescroller-game-source

그리고는 회전 코드입니다. 그래서 우리가 보는 것은 회전 된 이미지에서 직사각형을 보는 것입니다.
계산이 쉽지는 않지만, 회전 된 이미지를 사전 계산하는 대신 그릴 때 회전시킬 수 있으므로 원할 때 언제든지 각도를 변경할 수 있습니다 (불투명도 역시 btw) .

this.createImage = function(image , width, height) { 
    var fbWallImageCanvas = document.createElement('canvas'); 
    fbWallImageCanvas.width = width; 
    fbWallImageCanvas.height = height; 
      var fbWallImageCanvasContext = fbWallImageCanvas.getContext('2d'); 
    fbWallImageCanvasContext.drawImage(image,0,0); 
    return fbWallImageCanvas; 
}; 

그리고 이미지 회전 무 그래서 drawItem 변경 : 그냥 (캔버스 그리기 화상 드로잉보다 빠르다) 캔버스에 이미지를 저장하도록

그래서이 createImage의 단순화

this.drawItem = function(ct) { 
     var angle = 5; 
     var radian = angle * Math.PI/180; 
     ct.save(); 
     ct.translate(this.x + this.width/2 , this.y + this.height/2); 
     ct.rotate(radian); 
     ct.globalAlpha = 0.7; 
     ct.drawImage(fbc, - this.width/2, -this.height/2 , this.width, this.height); 
     ct.restore(); 
     this.animate(); 
    }; 

아마도 이것을 리팩토링하고 싶지만 그 아이디어를 볼 수 있습니다.

바이올린은 여기에 있습니다 : http://jsfiddle.net/DS2Sb/1/

0

작은 HTML5 튜토리얼에 대한 링크입니다 얼마전에 만들었습니다.

// save old coordinate system 
ctx.save(); 
// move to the middle of where we want to draw our image 
ctx.translate(canvas.width/2, canvas.height-64); 
// rotate around that point 
ctx.rotate(0.02 * (playerPosition.x)); 
//draw playerImage 
ctx.drawImage(playerImage, -playerImage.width/2, -playerImage.height/2); 
//and restore coordniate system to default 
ctx.restore();