1. 程式人生 > >百度T7 課程 canvas 學習 3---畫座標系

百度T7 課程 canvas 學習 3---畫座標系

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>網格</title>
	<style>
		#c1{
			border:1px solid black;
		}

	</style>

	<script>
			window.onload = function(){
				var oCanvas = document.getElementById('c1')
				var gd = oCanvas.getContext('2d')				
				// 你要畫一個表格: 
				// 你得思考,每個格子多大!
				var space = 20
				// 1, 得到 畫布的寬和高
				var cWidth = gd.canvas.width;
				var cHeight = gd.canvas.height;
				// 當你記不住api 的時候,就打印出來看看!
				var lines = Math.floor(cHeight/space)
				var cols = Math.floor(cWidth/space)
				for(let i = 0;i<lines;i++){
					gd.beginPath()
					gd.moveTo(0,space*i-0.5)
					gd.lineTo(cWidth,space*i-0.5)
					gd.strokeStyle='#aaa'
					gd.stroke();
				}
				// 畫第二個豎著的格子!
			
				for(let j = 0; j<cols;j++){
					gd.beginPath();
					gd.moveTo(space*j-0.5,0)
					gd.lineTo(space*j-0.5,cHeight)
					gd.strokeStyle="#aaa"
					gd.stroke()
				}



				// 下面是畫那個座標!
				
				// 1, everPadding(座標離 網格邊界的上下左右的距離!)
				var everPadding = 40
				// 起點(座標原點)
				var x0 = everPadding;
				var yo = cHeight -everPadding
				// x 軸,終點:
				var x1 = cWidth-everPadding;				
				// 豎著方向:
				
				// 畫著再說:
				gd.beginPath();
				gd.moveTo(x0,yo)
				gd.lineTo(x1,yo)
				gd.lineTo(x1-space,yo-space)
				gd.lineTo(x1-space,yo+space)
				gd.lineTo(x1,yo)
				gd.strokeStyle="red"
				gd.fillStyle="red"
				gd.stroke()
				gd.fill()

				gd.beginPath()
				gd.moveTo(x0,yo)
				gd.lineTo(x0,everPadding)
				gd.lineTo(x0-space,everPadding+space)
				gd.lineTo(x0+space,everPadding+space)
				gd.lineTo(x0,everPadding)
				gd.strokeStyle="red"
				gd.fillStyle="red"
				gd.stroke()
				gd.fill()


			}				
	</script>

</head>
<body>
	
	
		<canvas id="c1" width="500"  height="500"></canvas>


</body>
</html>

顯示: