圆角矩形虚线

时间:2012-03-27 20:06:11

标签: javascript html5 html5-canvas

我正在为canvascontext写一些额外的drawfunction。下面的代码应该允许用户绘制带有虚线或法线的圆角矩形。这几乎是完全正常工作的代码,但是在绘图的最后,在圆角处绘制了一条额外的线(我包括了该问题的图片)。请注意,只有当我绘制矩形虚线时才会出现此问题,另一个版本工作正常。

if (window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype.lineTo){
        CanvasRenderingContext2D.prototype.dashedLine = function(pt1, pt2, dashLen) {
                if (dashLen == undefined) dashLen = 6;

                var dX = pt2.x - pt1.x;
                var dY = pt2.y - pt1.y;
                var dashes = Math.floor(Math.sqrt(dX * dX + dY * dY) / dashLen);
                var dashX = dX / dashes;
                var dashY = dY / dashes;

                var q = 0;
                while (q++ < dashes) {
                 pt1.x += dashX;
                 pt1.y += dashY;
                 this[q % 2 == 0 ? 'moveTo' : 'lineTo'](pt1.x, pt1.y);
                }
                this[q % 2 == 0 ? 'moveTo' : 'lineTo'](pt2.x, pt2.y);
            };
        CanvasRenderingContext2D.prototype.roundRectangle = function(pt1, pt2, pt3, pt4, dashed, dashLen) {
              function line(ctx, x1, y1, x2, y2, dashed) {
                if (dashed) ctx.dashedLine({x:x1, y:y1}, {x:x2, y:y2});
                else {
                    ctx.lineTo(x2,y2);}
              }
              var radius = 8;
              this.beginPath();
              line(this, pt1.x + radius, pt1.y, pt2.x - radius, pt2.y, dashed);
              this.quadraticCurveTo(pt2.x, pt2.y, pt2.x, pt2.y + radius);
              line(this, pt2.x, pt2.y + radius, pt3.x, pt3.y - radius, dashed);
              this.quadraticCurveTo(pt3.x, pt3.y, pt3.x - radius, pt3.y);
              line(this, pt3.x - radius, pt3.y, pt4.x + radius, pt4.y, dashed);
              this.quadraticCurveTo(pt4.x, pt4.y, pt4.x, pt4.y - radius);
              line(this, pt4.x, pt4.y - radius, pt1.x, pt1.y + radius, dashed);
              this.quadraticCurveTo(pt1.x, pt1.y, pt1.x + radius, pt1.y);

              this.closePath();
              this.stroke();
              this.fill();
        }

}

enter image description here

有人知道这里可能出现什么问题吗?

1 个答案:

答案 0 :(得分:1)

this.closePath();行添加最后一条直线。只需删除它。

另外,要获得更好的结果,请移除this.beginPath();行,然后添加以下内容:

this.moveTo(pt1.x + radius, pt1.y);

检查修改后的代码:http://jsfiddle.net/W8b3e/