2012-09-27 5 views
0

일부 HTML5 애니메이션을 배우려고했지만 캔버스에서 마우스 위치를 기반으로 이미지를 회전하려고 시도하는 동안 회전 지점이 이미지 중심 대신 왼쪽 상단에 있습니다.HTML5 중심점에서 이미지 회전

제한된 경험으로 저는 이미지의 앵커 포인트를 변경할 수있는 옵션이 있음을 알고 있습니다. 가능한 회전이 일부 코너 대신 중심점을 중심으로 회전합니다. JavaScript에서로드 된 이미지를 중심 주위로 회전시킬 수있는 유사한 기능이 있습니까?

답변

3

당신은 transform-origin 속성과 회전의 (x, y)의 기원을 지정할 수 있습니다

transform-origin: 50% 50%; 

현재이 여전히 대부분의 공급 업체 접두사가 필요하지만 :

-webkit-transform-origin: 50% 50%; 
/* and others... */ 
0

좋아이 방법입니다 나는 그것을 작동시킬 수 있었다 :

애니메이션 루프를 포함하는 main.js

window.onload = function(){ 

/*variables*/ 
var canvas = document.getElementById('canvas'), 
context = canvas.getContext('2d'), 
mouse = utils.captureMouse(canvas), 
ship = new Ship(); 

ship.x = canvas.width/2; 
ship.y = canvas.with/2; 

/*animation loop*/ 
(function drawFrame(){ 

    window.requestAnimationFrame(drawFrame, canvas); 

    //clear rect tyhjentää koko canvasin 
    context.clearRect(0, 0, canvas.width + 1, canvas.height + 1); 

    var dx = mouse.x - alus.x, 
    dy = mouse.y - alus.y; 

    ship.rotation = Math.atan2(dy, dx); 
    ship.draw(context); 

})(); 

}

Ship.js는

function Ship(){ 

    this.x = 0;//x-sjainti 
    this.y = 0;//y-sijainti 
    this.rotation = 0; 
    this.img = new Image(); 
    this.img.src = "resources/img/ship2.png"; 
    this.imgW = this.img.width; 
    this.imgH = this.img.height; 

} 

    Ship.prototype.draw = function(context){ 

     context.save(); 

     context.translate(this.x, this.y); 
     context.rotate(this.rotation); 
     context.drawImage(this.img, this.imgW/2 * -1, this.imgH/2 * -1); 

     context.restore(); 

    } 

핵심 포인트는 imgWimgH 있습니다. drawImage-method에서 볼 수 있듯이, 이미지가 그려지는 위치는 객체의 크기의 절반만큼 뒤로 설정됩니다. 이것을 시도한 후 이것은 회전 지점의 중심에있는 것처럼 보였습니다.