基本框架
<body> <canvas id="myCanvas" width="200" height="100"></canvas> //看样子这里默认是用px做单位 </body>
<script> var c = document.getElementById("myCanvas"); var cxt = c.getContext("2d"); //这是内置的2d对象 </script>
案例
绘制一个矩形
cxt.fillRect(x,y,width,height); cxt.fillStyle = color;
绘制一条路径
cxt.moveTo(10,10); cxt.lineTo(150,50); cxt.lineTo(10,50); cxt.stroke();
绘制一个圆
cxt.fillStyle="#FF0000"; cxt.beginPath(); cxt.arc(70,18,15,0,Math.PI*2,true); cxt.closePath(); cxt.fill();
填充渐变
var grd=cxt.createLinearGradient(0,0,175,50); grd.addColorStop(0,"#FF0000"); grd.addColorStop(1,"#00FF00"); cxt.fillStyle=grd; cxt.fillRect(0,0,175,50);
填充图像
var img=new Image() img.src="flower.png" cxt.drawImage(img,0,0);