I've a little problem with canvas
I'm trying to make a paddle game , I want to rotate the upper paddle according to the mouse X-position My problem is that the drawing position is the top left of the paddle as normal and I want to change it after Drawing to be in the center of the paddle for rotation.
so the origin position of the paddle will be the center and every time the mouse moved the paddle will be rotated from the center not the top left.
here is updated function which invoked to updated the canvas.
function update() {
// Update scores
updateScore();
// Move the paddles on mouse move
// Here we will add another condition to move the upper paddle in Y-Axis
if(mouse.x && mouse.y) {
for(var i = 1; i < paddles.length; i++) {
p = paddles[i];
// the botoom paddle
if (i ==1){
p.x = mouse.x - p.w/2;
}else{
// the top paddle
ctx.save(); // saves the coordinate system
ctx.translate(W/4,H/2); // now the position (0,0) is found at (250,50)
ctx.rotate(0.30 * mouse.x); // rotate around the start point of your line
ctx.moveTo(0,0) // this will actually be (250,50) in relation to the upper left corner
ctx.lineTo(W/4,H/2) // (250,250)
ctx.stroke();
ctx.restore(); // restores the coordinate system back to (0,0)
}// end else
}//end for
}
Your translations are a little off, but it's easy to fix. Consider this alternative -- translate the context to the center of the paddle. After all, this is where you will be doing the rotation. Rotate the canvas, and then draw a horizontal line centered around the origin. I've codified my suggestion, and I've stored a few things in local variables to make it clearer.
var W = 200;
var H = 200;
var x = W / 2;
var y = H / 2;
var lineLength = 80;
ctx.save();
ctx.translate(x, y);
ctx.rotate(0.3 * mouse.X);
ctx.moveTo(-lineLength / 2,0, 0);
ctx.lineTo(lineLength / 2.0, 0);
ctx.stroke();
ctx.restore();