復(fù)制代碼代碼如下: // translate is move the startpoint to centera and back to top left corner function renderText(width, height, context) { context.translate(width/ 2, height / 2); // 中心點(diǎn)坐標(biāo)為(0, 0) context.font="18px Arial"; context.fill ; context.fillText("Please Press Esc to Exit Game",5,50); context.translate(-width/2, -height/2); // 平移恢復(fù)(0,0)坐標(biāo)為左上角 context.fillText("I'm Back to Top",5,50); }
復(fù)制代碼代碼如下: // 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(); }
旋轉(zhuǎn)(rotate) 旋轉(zhuǎn)角度rotate(Math.PI/8)
旋轉(zhuǎn)前的坐標(biāo)p(x, y)在對(duì)應(yīng)的旋轉(zhuǎn)后的坐標(biāo)P(rx, ry)為 Rx = x * cos(-angle) - y * sin(-angle); Ry = y * cos(-angle) + x * sin(-angle); 旋轉(zhuǎn)90度可以簡(jiǎn)化為: Rx = y; Ry = -x; Canvas中旋轉(zhuǎn)默認(rèn)的方向?yàn)轫槙r(shí)針方向。演示代碼如下:
復(fù)制代碼代碼如下: // 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); } }