复制代码代码如下: // translate is move the startpoint to centera and back to top left corner function renderText(width, height, context) { context.translate(width/ 2, height / 2); // 中心点坐标为(0, 0) context.font="18px Arial"; context.fill ; context.fillText("Please Press Esc to Exit Game",5,50); context.translate(-width/2, -height/2); // 平移恢复(0,0)坐标为左上角 context.fillText("I'm Back to Top",5,50); }
复制代码代码如下: // translation the rectangle. function drawPath(context) { context.translate(200,200); context.scale(2,2);// Scale twice size of original shape context.stroke "green"; context.beginPath(); context.moveTo(0,40); context.lineTo(80,40); context.lineTo(40,80); context.closePath(); context.stroke(); }
旋转(rotate) 旋转角度rotate(Math.PI/8)
旋转前的坐标p(x, y)在对应的旋转后的坐标P(rx, ry)为 Rx = x * cos(-angle) - y * sin(-angle); Ry = y * cos(-angle) + x * sin(-angle); 旋转90度可以简化为: Rx = y; Ry = -x; Canvas中旋转默认的方向为顺时针方向。演示代码如下:
复制代码代码如下: // new point.x = x * cos(-angle) -y * sin(-angle), // new point.y = y * cos(-angle) +x * sin(-angle) function renderRotateText(context) { context.font="24px Arial"; context.fill ; context.fillText("i'm here!!!",5,50); // rotate -90 degreee // context.rotate(-Math.PI/2); // context.fill ; // context.fillText("i'm here!!!", -400,30); // rotate 90 degreee context.rotate(Math.PI/2); context.fill ; context.fillText("i'm here!!!",350,-420); console.log(Math.sin(Math.PI/2)); // rotae 90 degree and draw 10 lines context.fill ; for(var i=0; i i++) { var x = (i+1)*20; var y = (i+1)*60; var newX = y; var newY = -x; context.fillRect(newX,newY, 200, 6); } }