在使用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>
