2.8.6_通过扩展CanvasRenderingContext2D来绘制虚线

来源:互联网 发布:淘宝食品主图 编辑:程序博客网 时间:2024/05/18 03:04

2.8.6_通过扩展CanvasRenderingContext2D来绘制虚线

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title>通过扩展CanvasRenderingContext2D来绘制虚线</title>        <style>            body{                background: #eee;            }            #canvas{                background: #fff;                cursor: pointer;                margin-left: 10px;                margin-top: 10px;                box-shadow: 4px 4px 8px rgba(0,0,0,0.5);                -webkit-box-shadow: 4px 4px 8px rgba(0,0,0,0.5);                -moz-box-shadow: 4px 4px 8px rgba(0,0,0,0.5);            }        </style>    </head>    <body>        <canvas id="canvas" width="600" height="400"></canvas>    </body>    <script>            /*             *CanvasRenderingContext2D 对象提供了一组用来在画布上绘制的图形函数。             * */        var canvas = document.getElementById('canvas'),            context = canvas.getContext('2d');            //得到moveTo函数原型的引用            moveToFunction = CanvasRenderingContext2D.prototype.moveTo;            //CanvasRenderingContext2D新添加一个lastMoveToLocation属性            CanvasRenderingContext2D.prototype.lastMoveToLocation = {};            //重写moveTo函数的原型,将经x,y点添加给lastMoveToLocation对象            CanvasRenderingContext2D.prototype.moveTo = function(x,y){                moveToFunction.apply(context,[x,y]); //继续原moveTo函数的全部属性跟方法                this.lastMoveToLocation.x = x;//这里的this应该指的是CanvasRenderingContext2D这个对象                this.lastMoveToLocation.y = y;            }            //CanvasRenderingContext2D新添加一个dashedLineTo方法,这样得到的是虚线的路径,并没有调用stroke方法描边            CanvasRenderingContext2D.prototype.dashedLineTo = function (x,y,dashLenth){                dashLenth = dashLenth ===undefined? 5:dashLenth;                var startX=this.lastMoveToLocation.x;                var startY = this.lastMoveToLocation.y;                var deltaX = x-startX;                var deltaY = y-startY;                //得到有多少段虚线                var numDashes = Math.floor(Math.sqrt(deltaX*deltaX + deltaY*deltaY)/dashLenth);                for(var i=0;i<numDashes;i++){                    this[i%2===0? 'moveTo':'lineTo'](startX+(deltaX/numDashes)*i,startY+(deltaY/numDashes)*i);                }                //最后调用这个是防止上面numDashes是奇数的话,最后调用的lineTo,不能把新的最后的点赋予lastMoveToLocation属性中                this.moveTo(x,y);            }            context.lineWidth = 3;            context.strokeStyle = 'blue';            context.moveTo(20,20);            context.d  ashedLineTo(context.canvas.width-20,20);            context.dashedLineTo(context.canvas.width-20,context.canvas.height-20);            context.dashedLineTo(20,context.canvas.height-20);            context.dashedLineTo(20,20);            context.dashedLineTo(context.canvas.width-20,context.canvas.height-20);            context.stroke();    </script></html>
0 0
原创粉丝点击