就不多介绍了,单纯为了回忆一下canvas的渐变属性的写法;
绘制渐变图形
效果:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <!--linearGradient--> <canvas id="canvas" width="500" height="500"></canvas> <script> function draw(id){ var canvas=document.getElementById(id); var context=canvas.getContext("2d"); var g1=context.createLinearGradient(0,0,0,300); g1.addColorStop(0,"rgb(250,255,0)"); g1.addColorStop(1,"rgb(0,255,255)"); context.fillStyle=g1; context.fillRect(0,0,500,500); var g2=context.createLinearGradient(0,0,300,0); g2.addColorStop(0,"rgba(0,0,255,0.5)"); g2.addColorStop(1,"rgba(255,0,0,0.5)"); for(var i=0;i<10;i++){ context.beginPath(); context.fillStyle=g2; context.arc(i*25,i*25,i*10,0,Math.PI*2,true); context.closePath(); context.fill(); } } window.onload=function(){ draw("canvas"); } </script> </body> </html>
绘制径向渐变
效果
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <!--绘制径向渐变--> <canvas id="canvas" width="500" height="500"></canvas> <script> function draw(id){ var canvas=document.getElementById(id); if(canvas==null){ return false } var context=canvas.getContext("2d"); var g1=context.createRadialGradient(400,0,0,400,0,400); g1.addColorStop(0.1,"rgb(255,255,0"); g1.addColorStop(0.3,"rgb(255,0,255)"); g1.addColorStop(1,"rgb(0,255,255)"); context.fillStyle=g1; context.fillRect(0,0,500,500); } window.onload=function(){ draw("canvas") } </script> </body> </html>
简单动画
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <canvas id="canvas" width="500" height="500"></canvas> <button id="startBtn">开始绘制</button> <script> function draw(id){ var canvas=document.getElementById(id); if(canvas==null){ return false } var context=this.context=canvas.getContext('2d'); context.fillStyle="#eeeeee"; context.fillRect(0,0,500,500); context.translate(250,50); context.fillStyle="rgba(255,0,0,0.25)"; setInterval(function(){ one() },100) } function one(){ var context=this.context; context.translate(25,25); context.scale(0.95,0.95); context.rotate(Math.PI/10); context.fillRect(0,0,100,50) } var startBtn=document.getElementById("startBtn"); startBtn.addEventListener("click",function(){ draw("canvas"); }) </script> </body> </html>