了解canvas的曲線路徑,實現的簡單太極圖
阿新 • • 發佈:2019-01-08
自己 分享圖片 com family lin key tel tro etc
本例子主要應用canvas的曲線路徑arc().
*.arc(x,y,r,start,end,counterclockwise)
- (x,y) 弧形的圓心
- r 弧形半徑
- start,end 弧形起止點
- counterclockwise 是否逆時針,true是逆時針
需要註意畫圓時不事先定位到圓心會是如下效果:
左圖用fill()填充,右圖用stroke畫輪廓,用stroke()時不會自動閉合圖形,需要在stroke之前調用closePath().
利用moveTo()事先定位到圓心坐標會有如下效果:
此效果只對fill()有效,對stroke達不到此效果,stroke可以集合lineTo()實現。
moveTo定位的坐標點會與弧形起始點start相連,用fill()填充圖形,覆蓋了連接的線所以會有如上的效果圖。
如果moveTo和stroke連用則會有以下效果(更能直接觀察到定點坐標和start點相連):
然後附上弧線取值圖:
進入正題,以下實現太極圖勻速旋轉的效果
- html文件中寫入
<canvas id="canvas" width="200" height="200px" radius="50px"></canvas>
要註意canvas的寬高,cancas有默認的寬高,但是建議自己設置好,一旦所畫圖形超出canvas的默認寬高值,就可能出現你的畫找不到了的效果。(一開始沒註意,總以為自己寫的代碼拼寫或者大小寫錯了。。檢查好多遍確認沒問題,參考別人代碼才發現,過於專註調整路徑,忽略了圖畫坐標已超出畫布。。。不在畫布上畫能看見畫才怪!)
- script中寫入
var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); //畫整個大圓 ctx.beginPath(); ctx.lineWidth="2"; ctx.arc(100,100,100,0,Math.PI*2,false); ctx.stroke(); ctx.closePath(); //畫黑色半邊圓 ctx.beginPath(); ctx.arc(100,100,100,Math.PI*3/2,Math.PI/2,true); ctx.fill(); ctx.closePath(); //畫黑色小半邊圓ctx.beginPath(); ctx.arc(100,50,50,Math.PI*3/2,Math.PI/2,false); ctx.fill(); ctx.closePath(); //畫白色小半邊圓 ctx.beginPath(); ctx.fillStyle="#fff"; ctx.arc(100,149,49,Math.PI*3/2,Math.PI/2,true); ctx.fill(); ctx.closePath(); //畫白色小圓 ctx.beginPath(); ctx.fillStyle="#fff"; ctx.arc(100,50,10,0,Math.PI*2,false); ctx.fill(); ctx.closePath(); //畫黑色小圓 ctx.beginPath(); ctx.fillStyle="#000"; ctx.arc(100,150,10,0,Math.PI*2,false); ctx.fill(); ctx.closePath();
主要用畫圓函數arc()實現整個太極圖。
- 加入動態效果,css文件加入
canvas{ box-shadow: 0px 0px 25px #000; border-radius:100px; animation:myan 10s linear infinite; } @keyframes myan{ 0%{transform:rotate(0deg);} 50%{transform:rotate(180deg);} 100%{transform:rotate(360deg);} }
box-shadow加陰影
transform加旋轉動畫效果
了解canvas的曲線路徑,實現的簡單太極圖