利用canvas绘制图形需要有4个步骤:
1、开创路径,创建图形的路径
2、关闭路径和设定绘制样式
3、调用绘制方法
4、绘制路径
canvas画圆
<body onload="draw('canvas')">
<script>
function draw(id){
var canvas=document.getElementById(id);
if(canvas==null){
return false;
}
var context=canvas.getContext("2d");
context.fillStyle="#cccccc";
context.width=600;
context.heught=600;
context.fillRect(0,0,600,600);
for(var i=0;i<=10;i++){
context.beginPath();
context.arc(i*25,i*25,i*10,0,Math.PI*2,true);
context.closePath();
context.fillStyle="rgba(255,0,0,0.25)";
context.fill();
}
}
</script>
<canvas id="canvas" style="width:600px;height:600px"></canvas>
</body>
利用move to和line to来绘制一个带角的圆形
代码示例:
<body onload="draw('canvas')">
<script>
function draw(id){
var canvas=document.getElementById(id);
var context=canvas.getContext("2d");
context.width=500;
context.heught=500;
context.fillStyle="#cccccc";
context.fillRect(0,0,300,300);
var dx=150;
var dy=80;
var s=70;
context.beginPath();
context.fillStyle="rgb(100,255,100)";
context.strokeStyle="rgb(0,0,100)";
var x=Math.sin(0);
var y=Math.cos(0);
var dig=Math.PI/15*11;
for(var i=0;i<=30;i++){
var x=Math.sin(i*dig);
var y=Math.cos(i*dig);
context.lineTo(dx+x*s,dy+y*s);
}
context.closePath();
context.fill();
context.stroke();
}
</script>
<canvas id="canvas" style="width:300px;height:300px"></canvas>
</body>
|
|