2015-06-29 83 views
0

我一直在努力解决这个问题,并试图让它工作,但现在我几乎陷入了困境。基于鼠标的X和Y位置旋转矩形

我想要这个矩形跟随这个鼠标位置并正确旋转。它遵循鼠标,但我的角度旋转似乎关闭。任何帮助或指导,我不知道我在这里做错了什么。

下面是有它的角度代码:

function createBoat() { 
    var angle = Math.atan2(
      boat.y - mousePos.y, 
      boat.x - mousePos.x 
     ) * 180/Math.PI; 
    ship_context.rotate(angle); 
    ship_context.fillRect(boat.x, boat.y, boat.width, boat.height); // create some shape, there is nothing on the canvas yet 
} 

这里是我的循环

function loop() { 
    ship_context.clearRect(0, 0, window.innerWidth, window.innerHeight); 
    moveBoat(); 
    time = Date.now(); 
    createBoat(); 

    setTimeout(loop, 1000/60); 
} 

这里有一个演示:http://staging.interactivemechanics.com/chop/row3.html


此外,阿里纳斯,我的工作现在有基本的形状。但我打算把一切都翻译成图像。矩形将是一条船,我有一个单独的页面,我在池塘里有叶子移动。我也有那部分工作与碰撞检测。我想知道一个图书馆是否会更好地在这里使用,或者如果我应该坚持使用画布?

这里的其他演示:http://staging.interactivemechanics.com/chop/row2.html与移动的东西

回答

1

如果你想只旋转了船,你首先需要翻译(姑且称之为固定)在画布上的位置,和旋转在这一点上。为避免你的船到过旋转,我们还需要重新设置旋转我们正在绘制完船后

试试这个:

function createBoat() { 
    var angle = Math.atan2(
      boat.y - mousePos.y, 
      boat.x - mousePos.x 
     ) * 180/Math.PI; 
    ship.context.save(); //save the settings of the canvas 
    ship_context.translate(boat.x+boat.width/2,boat.y+boat.height/2); //move focus to boat position (middle of the boat) 
    ship_context.rotate(angle); 
    ship_context.fillRect(-boat.width/2, -boat.height/2); // create some shape, there is nothing on the canvas yet 
    ship_context.restore(); //putting everything back in place 
} 
+0

谢谢!这就是诀窍,我将不得不更多地阅读,你有什么建议吗? – Jeff

+0

这是一个很好的教程,解释了图像的旋转,包括save(),rotate()和restore()http://creativejs.com/2012/01/day-10-drawing-rotated-images-into-帆布/ – Niddro