Canvas基础
大道至简
html
index.html
<!DOCTYPE HTML> <html style="height:100%"> <head> <title>canvas基础</title> <meta charset="utf-8"/> <script src="canvas_demo.js"></script> </head> <body style="height:100%"> <canvas id="canvas"> 请升级浏览器 </canvas> </body> </html>
js
canvas_demo.js
var canvas=document.getElementById("canvas"); var context=canvas.getContext("2d"); canvas.width=document.body.clientWidth; canvas.height=document.body.clientHeight; context.beginPath() context.moveTo(0,0); context.lineTo(500,500); context.lineWidth=5; context.closePath() context.strokeStyle="red"; context.stroke(); context.beginPath() context.arc(500,200,150,0,2*Math.PI,true); context.closePath() context.strokeStyle="blue"; context.stroke(); context.beginPath() context.moveTo(800,200) context.lineTo(1200,100) context.lineTo(1400,500) context.closePath() context.fill() context.fillRect(1400,300,100,100) context.beginPath() context.moveTo(1400,100) context.lineTo(1600,400) context.closePath() var gnt1=context.createLinearGradient(1400,100,1600,400) gnt1.addColorStop(0,'red') gnt1.addColorStop(1,'yellow') context.strokeStyle=gnt1 context.stroke() var gnt2=context.createLinearGradient(100,0,300,0) gnt2.addColorStop(0,'green') gnt2.addColorStop(0.5,'red') gnt2.addColorStop(1,'yellow') context.fillStyle=gnt2 context.fillRect(100,600,200,100) context.beginPath() context.arc(600,800,100,0,1.5*Math.PI,true) context.closePath() context.stroke() var gtn=context.createRadialGradient(1200,600,50,1200,700,200) gtn.addColorStop(1,"blue") gtn.addColorStop(0,"red") context.fillStyle=gtn context.fillRect(1000,500,400,400)