扩充canvas的方法

了解下知识点:

1.prototype 属性使您有能力向对象添加属性和方法。

2.CanvasRenderingContext2D 

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,老师讲的很详细。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值