了解下知识点:
1.prototype 属性使您有能力向对象添加属性和方法。
CanvasRenderingContext2D 接口提供的 2D 渲染背景用来绘制<canvas>元素,为了获得这个接口的对象,需要在 <canvas> 上调用 getContext() ,并提供一个 "2d" 的参数。
canvas所有的API接口都是放在这里的,所以用这个扩充canvas的方法
下面我们来做个列子:在canvas内绘制五角星的方法
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>椭圆</title>
</head>
<body>
<canvas id="canvas" style="border:1px solid #aaa;display:block;margin:50px auto;">
当前浏览器不支持Canvas,请更换浏览器后再试
</canvas>
<script>
var canvas = document.getElementById("canvas");
canvas.width = 800;
canvas.height = 800;
var context = canvas.getContext("2d");
context.lineWidth = 10;
context.fillStyle="#f00";
context.strokeStyle="black";
//num 是你要绘制几角形
CanvasRenderingContext2D.prototype.fillStar=function (r,R,x,y,rot,num) {
this.beginPath();
for(var i=0;i<num;i++){
this.lineTo(Math.cos(2*((90-(360/num))+i*(360/num)-rot)*Math.PI / 360)*R+x,
-Math.sin(2*((90-(360/num))+i*(360/num)-rot)*Math.PI / 360)*R+y );
this.lineTo(Math.cos(2*((90-(360/2/num))+i*(360/num)-rot)*Math.PI / 360)*(R/2)+x,
-Math.sin(2*((90-(360/2/num))+i*(360/num)-rot)*Math.PI / 360)*(R/2)+y );
}
this.closePath();
this.fill();
this.stroke();
}
context.fillStar(150,300,400,400,0,5);
</script>
</body>
</html>
当然扩充canvas的方法不会是这么简单的,此方法来不完全脱离canvas,因为lineTo()还要依靠moveTo().所以这还不是完全属于自己的API。有兴趣的朋友看下,扩展canvas的context,老师讲的很详细。