<script type="text/javascript">
function Draw() {
var c = document.getElementById("myCanvas");
c.width = 500;
c.height = 500;
var ctx = c.getContext("2d");
script>
<body>
<canvas id="myCanvas">canvas>
<input type="button" value="画图" onclick="Draw()"/>
body>
1.画矩形
ctx.fillStyle = "#ff0000";
ctx.fillRect(0,0,200,200);
2.画直线
ctx.moveTo(0,0);
ctx.lineTo(200,200);
ctx.stroke();
3.画圆
ctx.beginPath();
//第一、二的参数设置起始位置,第三个参数设置半径,第四个开始的角度,第五个结束的角度,第六个是否按照顺时针绘制 ctx.arc(100,100,50,0,Math.PI*2,true);
ctx.closePath();
ctx.fill();
4.画三角形
ctx.strokeStyle = "#ff0000";
ctx.beginPath();
ctx.moveTo(25,25);
ctx.lineTo(150,25);
ctx.lineTo(25,150);
ctx.closePath();
ctx.stroke();
5.画贝塞尔曲线
ctx.lineWidth = 5;
ctx.strokeStyle = "#ff0000";
ctx.beginPath();
ctx.moveTo(0,200);
//ctx.quadraticCurveTo(75,50,300,200);
ctx.bezierCurveTo(205,56,239,439,429,236);
ctx.stroke();
6.保存与恢复状态
ctx.fillStyle = "#ff0000";
ctx.strokeStyle = "#000000";
ctx.fillRect(20,20,200,100);
ctx.strokeRect(20,20,200,100);
ctx.fill();
ctx.stroke();
//保存状态
ctx.save();
ctx.fillStyle = "#00ff00";
ctx.strokeStyle = "#0000ff";
ctx.fillRect(200,200,100,50);
ctx.strokeRect(200,200,100,50);
ctx.fill();
ctx.stroke();
//恢复状态
ctx.restore();
ctx.fillRect(300,300,100,100);
ctx.strokeRect(300,300,100,100);
7.缩放位移旋转
ctx.fillStyle = "#00ff00";
//ctx.translate(100,50);
//ctx.rotate(30*Math.PI/180);
ctx.scale(2,1);
ctx.rect(0,0,150,100);
ctx.fill();
8.图形的组合
//图形的组合
onload = function () {
var c = document.getElementById("myCanvas");
c.width = 500;
c.height = 500;
var ctx = c.getContext("2d");
ctx.fillStyle = "#00ff00";
ctx.fillRect(50,25,100,100);
ctx.globalCompositeOperation = "destination-over";
ctx.fillStyle = "#0000ff";
ctx.beginPath();
ctx.arc(150,125,50,0,Math.PI*2,true);
ctx.closePath();
ctx.fill();
}