1. 程式人生 > >繪製貝塞爾曲線()

繪製貝塞爾曲線()

<!DOCTYPE html>
<html>
<style type="text/css">
    body{text-align: center;}
    #can{ border:1px solid black;}
</style>
<body>
    <h2>beisaier</h2>
    <canvas id="can" width="400" height="300" ></canvas>
</body>
    <script>
        var a=can.getContext("2d");
        var b=can.width,c=can.height;
        var p=function(x,y){
            this.x=x;
            this.y=y;
        }
        var v=[];
        function ccp(x,y)
        {
            if(v.length<4)
            {
                v.push(new p(x,y));
            }
        }
        function dp()//繪製控制點
        {
            for(var i=0;i< v.length;i++)
            {
                var e="red";
                if(i<2)
                {
                    e="green";
                }
                a.strokeStyle=e;
                a.strokeRect(v[i].x-5,v[i].y-5,10,10);
            }
        }
        function is(p1,p2,w,h)//判斷一個點是否在以p2為中心的矩形中
        {
            return p1.x>=p2.x-w&&p1.x<p2.x+w&&p1.y>p2.y-h&&p1.y<=p2.y+h;
        }
        function getid(pp)判斷一個點在哪一個控制區域中
        {
            var id=-1;
            for(var i=0;i< v.length;i++)
            {
                if(is(pp,v[i],10,10))
                {
                    return i;
                }
            }
            return id;
        }
        function db()
        {
            a.strokeStyle="gray";
            a.beginPath();
            a.moveTo(v[0].x,v[0].y);
            a.lineTo(v[2].x,v[2].y);
            a.stroke();
            a.moveTo(v[1].x,v[1].y);
            a.lineTo(v[3].x,v[3].y);
            a.stroke();
        }
        function dbe()
        {
            a.beginPath();
            a.strokeStyle="red";
            a.moveTo(v[0].x,v[0].y);
            a.bezierCurveTo(v[2].x,v[2].y,v[3].x,v[3].y,v[1].x,v[1].y);
            a.stroke();
        }
        function d()
        {
            dp();
            if(v.length>3)
            {
                db();
                dbe();
            }
        }
        var sb=new p(-1,-1),sid;
        can.onmousedown=function(ee){//滑鼠功能設定
            var x= ee.offsetX,y= ee.offsetY;
            sb.x=x;sb.y=y;
            ccp(x,y);
            d();
            if(v.length>3)
            {
                sid=getid(sb);
                if(sid>=0)
                {
                    can.onmousemove=function(ee){
                        v[sid].x= ee.offsetX;
                        v[sid].y= ee.offsetY;
                        a.clearRect(0,0,400,300);
                        d();
                    }
                }
            }

        }
        can.onmouseup=function(){//必要的取消滑鼠move的設定
            this.onmousemove=null;
        }

    </script>

</html>