<canvas> </canvas>中的虚线描边

时间:2011-01-02 01:56:36

标签: javascript html5 canvas

我想不可能设置CSS这样的笔触属性很容易。使用CSS时,我们在绘制线条/笔划时使用虚线,点线,实体但在画布上这似乎不是一种选择。你是如何实现这个的?

我已经看过一些例子,但他们真的很渴望这种愚蠢的功能。

例如:

http://groups.google.com/group/javascript-information-visualization-toolkit/browse_thread/thread/22000c0d0a1c54f9?pli=1

11 个答案:

答案 0 :(得分:65)

有趣的问题!我写了一个虚线的自定义实现;你可以try it out here。我选择了Adobe Illustrator的路线,并允许您指定一个短划线/间隙长度数组。

对于stackoverflow后代,这是我的实现(略微改变了s / o线宽):

var CP = window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype;
if (CP && CP.lineTo){
  CP.dashedLine = function(x,y,x2,y2,dashArray){
    if (!dashArray) dashArray=[10,5];
    if (dashLength==0) dashLength = 0.001; // Hack for Safari
    var dashCount = dashArray.length;
    this.moveTo(x, y);
    var dx = (x2-x), dy = (y2-y);
    var slope = dx ? dy/dx : 1e15;
    var distRemaining = Math.sqrt( dx*dx + dy*dy );
    var dashIndex=0, draw=true;
    while (distRemaining>=0.1){
      var dashLength = dashArray[dashIndex++%dashCount];
      if (dashLength > distRemaining) dashLength = distRemaining;
      var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
      if (dx<0) xStep = -xStep;
      x += xStep
      y += slope*xStep;
      this[draw ? 'lineTo' : 'moveTo'](x,y);
      distRemaining -= dashLength;
      draw = !draw;
    }
  }
}

要绘制一条从20,150170,10的行,其中包含30px长的短划线,后跟10px的间隙,您可以使用:

myContext.dashedLine(20,150,170,10,[30,10]);

要绘制交替的短划线和点,请使用(例如):

myContext.lineCap   = 'round';
myContext.lineWidth = 4; // Lines 4px wide, dots of diameter 4
myContext.dashedLine(20,150,170,10,[30,10,0,10]);

0的“非常短”的短划线长度与圆形的lineCap相结合会产生沿着你的线的点。

如果有人知道如何访问画布上下文路径的当前点,我很想知道它,因为它允许我将其写为ctx.dashTo(x,y,dashes)而不是要求你重新指定方法调用中的起点。

答案 1 :(得分:42)

这个Phrogz代码的简化版本利用了Canvas的内置转换功能,并且还处理特殊情况,例如:当dx = 0时

var CP = window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype;
if (CP.lineTo) {
    CP.dashedLine = function(x, y, x2, y2, da) {
        if (!da) da = [10,5];
        this.save();
        var dx = (x2-x), dy = (y2-y);
        var len = Math.sqrt(dx*dx + dy*dy);
        var rot = Math.atan2(dy, dx);
        this.translate(x, y);
        this.moveTo(0, 0);
        this.rotate(rot);       
        var dc = da.length;
        var di = 0, draw = true;
        x = 0;
        while (len > x) {
            x += da[di++ % dc];
            if (x > len) x = len;
            draw ? this.lineTo(x, 0): this.moveTo(x, 0);
            draw = !draw;
        }       
        this.restore();
    }
}

我认为我的计算是正确的,似乎表现良好。

答案 2 :(得分:9)

目前至少setLineDash([5,10])适用于Chrome,而ctx.mozDash = [5,10]适用于FF:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

if ( ctx.setLineDash !== undefined )   ctx.setLineDash([5,10]);
if ( ctx.mozDash !== undefined )       ctx.mozDash = [5,10];

ctx.beginPath();              
ctx.lineWidth="2";
ctx.strokeStyle="green";
ctx.moveTo(0,75);
ctx.lineTo(250,75);
ctx.stroke();

设置为null会使该行变为实线。

答案 3 :(得分:6)

Mozilla一直致力于implementation of dashed stroking画布,所以我们可能会在不久的将来看到它添加到规范中。

答案 4 :(得分:6)

Phroz的解决方案很棒。但是当我在我的应用程序中使用它时,我发现了两个错误。

下面的代码被调试(并且为了可读性而重构)版本的Phroz的。

// Fixed: Minus xStep bug (when x2 < x, original code bugs)
// Fixed: Vertical line bug (when abs(x - x2) is zero, original code bugs because of NaN)
var CP = window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype;
if(CP && CP.lineTo) CP.dashedLine = function(x, y, x2, y2, dashArray){
    if(! dashArray) dashArray=[10,5];
    var dashCount = dashArray.length;
    var dx = (x2 - x);
    var dy = (y2 - y);
    var xSlope = (Math.abs(dx) > Math.abs(dy));
    var slope = (xSlope) ? dy / dx : dx / dy;

    this.moveTo(x, y);
    var distRemaining = Math.sqrt(dx * dx + dy * dy);
    var dashIndex = 0;
    while(distRemaining >= 0.1){
        var dashLength = Math.min(distRemaining, dashArray[dashIndex % dashCount]);
        var step = Math.sqrt(dashLength * dashLength / (1 + slope * slope));
        if(xSlope){
            if(dx < 0) step = -step;
            x += step
            y += slope * step;
        }else{
            if(dy < 0) step = -step;
            x += slope * step;
            y += step;
        }
        this[(dashIndex % 2 == 0) ? 'lineTo' : 'moveTo'](x, y);
        distRemaining -= dashLength;
        dashIndex++;
    }
}

答案 5 :(得分:5)

有一种更简单的方法可以做到这一点。根据{{​​3}},strokeStyle接受字符串,CanvasGradients或CanvasPatterns。所以我们只拍这样的图像:

  <img src="images/dashedLineProto.jpg" id="cvpattern1" width="32" height="32" />

将其加载到画布中,并用它绘制我们的小矩形。

  var img=document.getElementById("cvpattern1");
  var pat=ctx.createPattern(img,"repeat");
  ctx.strokeStyle = pat;
  ctx.strokeRect(20,20,150,100);

这不会产生完美的虚线,但它真的很简单,可以修改。当您绘制水平或垂直的线条时,结果当然可能变得不完美,虚线图案可能会有帮助。

PS。请记住,当您尝试在代码中使用来自外部源的imgs时,SOP会适用。

答案 6 :(得分:3)

HTML5 Canvas规范目前不支持虚线。

检查一下:

http://davidowens.wordpress.com/2010/09/07/html-5-canvas-and-dashed-lines/

查看Raphael JS Library:

http://raphaeljs.com/

答案 7 :(得分:2)

Firefox at least

支持它
ctx.mozDash = [5,10];

似乎ctx.webkitLineDash之前有效,但他们删除了它,因为它有一些compabillity issues

W3C specsctx.setLineDash([5,10]);但似乎还没有在任何地方实施。

答案 8 :(得分:2)

我修改了dashedLine函数以添加对偏移的支持。如果浏览器支持ctx.setLineDashctx.lineDashOffset,它会使用原生虚线。

示例:http://jsfiddle.net/mLY8Q/6/

var CP = window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype;
if (CP.lineTo) {

    CP.dashedLine = CP.dashedLine || function (x, y, x2, y2, da, offset) {

        if (!da) da = [10, 5];
        if (!offset) offset = 0;

        if (CP.setLineDash && typeof (CP.lineDashOffset) == "number") {
            this.save();
            this.setLineDash(da);
            this.lineDashOffset = offset;

            this.moveTo(x, y);
            this.lineTo(x2, y2);

            this.restore();
            return;
        }


        this.save();
        var dx = (x2 - x),
            dy = (y2 - y);
        var len = Math.sqrt(dx * dx + dy * dy);
        var rot = Math.atan2(dy, dx);
        this.translate(x, y);
        this.moveTo(0, 0);
        this.rotate(rot);
        var dc = da.length;
        var di = 0;

        var patternLength = 0;
        for (var i = 0; i < dc; i++) {
            patternLength += da[i];
        }
        if (dc % 2 == 1) {
            patternLength *= 2;
        }

        offset = offset % patternLength;
        if (offset < 0) {
            offset += patternLength;
        }

        var startPos = 0;
        var startSegment = 0;
        while (offset >= startPos) {



            if (offset >= startPos + da[startSegment % dc]) {
                startPos += da[startSegment % dc];
                startSegment++;
            } else {
                offset = Math.abs(offset - startPos);
                break;
            }


            if (startSegment > 100) break;
        }
        draw = startSegment % 2 === 0;
        x = 0;
        di = startSegment;


        while (len > x) {
            var interval = da[di++ % dc];
            if (x < offset) {
                interval = Math.max(interval - offset, 1);
                offset = 0;
            }

            x += interval;
            if (x > len) x = len;
            draw ? this.lineTo(x, 0) : this.moveTo(x, 0);
            draw = !draw;
        }
        this.restore();
    };
}

答案 9 :(得分:2)

看起来context.setLineDash几乎已经实现了。 请参阅this

“context.setLineDash([5])  将产生虚线,其中破折号和空格的大小均为5像素。 “

答案 10 :(得分:1)

我在Mozilla规范中找到了属性mozDashmozDashOffset
http://mxr.mozilla.org/mozilla-central/source/dom/interfaces/canvas/nsIDOMCanvasRenderingContext2D.idl

他们被用来控制破折号,但我没有使用它们。

相关问题