在使用canvas的時候,原點坐標在左上角,這個很犯人,因為一般的坐標基本都是在左下角,即笛卡爾坐標系,那怎么進行轉變呢,在這里用到了canvas的translate,rotate,和scale進行轉換,話不多說,上代碼:
<!DOCTYPE html> <html lang="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <head> <title>笛卡爾坐標系</title> </head> <body onload="draw()"> <canvas id="myCanvus" width="440px" height="240px" style="border:1px dashed black;"> 出現文字表示你的瀏覽器不支持HTML5 </canvas> </body> </html> <script type="text/javascript"> <!-- function draw(){ var canvas=document.getElementById("myCanvus"); var canvasWidth=440; var canvasHeight=240; var context=canvas.getContext("2d"); context.fillStyle = "white"; context.fillRect(0, 0, canvasWidth, canvasHeight); context.strokeStyle = "black"; context.fillStyle = "black"; context.save(); // 進行坐標變換:把原點放在左下角,東方為X軸正向,北方為Y軸正向 context.save(); context.translate(0,canvasHeight); context.rotate(getRad(180)); context.scale(-1,1); // 畫折線 context.beginPath(); context.moveTo(0, 0); context.lineTo(50, 50); context.stroke(); context.closePath(); context.restore(); } function getRad(degree){ return degree/180*Math.PI; } //--> </script>