JasperTack
JasperTack

Reputation: 4447

rounded rectangle dashed lines

I am writing some additional drawfunction for the canvascontext. The code below should alow the user to draw rounded rectangles with dashed lines or normal lines. This is almost fully working code, but at the end of the drawing, there is an additional line drawn at a rounded corner (I included a picture of that problem). Note that this problem only occurs when I draw the rectangle dashed, the other version works perfect.

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

Does anybody know what could be the problem here?

Upvotes: 1

Views: 1075

Answers (1)

Juan Mellado
Juan Mellado

Reputation: 15113

The this.closePath(); line add that last straight line. Just remove it.

Also, to get a better result, remove the this.beginPath(); line and add the following one instead:

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

Check the modified code: http://jsfiddle.net/W8b3e/

Upvotes: 1

Related Questions