Ответ 1
Похоже, вы хотите повернуть прямоугольник вокруг его центральной точки.
Красный прямоугольник оригинален, желтый прямоугольник вращается вокруг центральной точки.
Для этого вам нужно сначала context.translate
до центральной точки прямой перед вращением.
// move the rotation point to the center of the rect
ctx.translate( x+width/2, y+height/2 );
// rotate the rect
ctx.rotate(degrees*Math.PI/180);
Обратите внимание, что контекст теперь находится в его повернутом состоянии.
Это означает, что позиция чертежа [0,0] визуально находится на [x + width/2, y + height/2].
Итак, вы должны нарисовать вращающийся прямоугольник в [-width/2, -height/2] (не на исходном невращаемом x/y).
// draw the rect on the transformed context
// Note: after transforming [0,0] is visually [-width/2, -height/2]
// so the rect needs to be offset accordingly when drawn
ctx.rect( -width/2, -height/2, width,height);
Вот код и скрипт: http://jsfiddle.net/m1erickson/z4p3n/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var startX=50;
var startY=80;
// draw an unrotated reference rect
ctx.beginPath();
ctx.rect(startX,startY,100,20);
ctx.fillStyle="blue";
ctx.fill();
// draw a rotated rect
drawRotatedRect(startX,startY,100,20,45);
function drawRotatedRect(x,y,width,height,degrees){
// first save the untranslated/unrotated context
ctx.save();
ctx.beginPath();
// move the rotation point to the center of the rect
ctx.translate( x+width/2, y+height/2 );
// rotate the rect
ctx.rotate(degrees*Math.PI/180);
// draw the rect on the transformed context
// Note: after transforming [0,0] is visually [x,y]
// so the rect needs to be offset accordingly when drawn
ctx.rect( -width/2, -height/2, width,height);
ctx.fillStyle="gold";
ctx.fill();
// restore the context to its untranslated/unrotated state
ctx.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>