【问题标题】:rounded rectangle dashed lines圆角矩形虚线
【发布时间】:2012-03-28 06:07:26
【问题描述】:

我正在为画布上下文编写一些额外的绘图函数。下面的代码应该允许用户用虚线或法线绘制圆角矩形。这几乎是完全可以工作的代码,但是在绘图的最后,在圆角处画了一条额外的线(我附上了那个问题的图片)。请注意,此问题仅在我绘制虚线矩形时出现,其他版本完美运行。

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();
        }

}

有人知道这可能是什么问题吗?

【问题讨论】:

    标签: javascript html html5-canvas


    【解决方案1】:

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

    另外,为了获得更好的结果,请删除 this.beginPath(); 行并添加以下行:

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

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

    【讨论】:

    • 感谢您解决了这个问题,但我想添加填充选项,以便为背景着色。当我这样做时,只有二次曲线区域是彩色的,所以我需要那条路径。我在这里更改了代码:jsfiddle.net/W8b3e/2
    猜你喜欢
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多