如何在画布中绘制虚线矩形?

时间:2011-12-30 08:22:05

标签: javascript html5 html5-canvas

我的任务是在画布上进行裁剪,我已经完成了所有逻辑,但还有一项要求尚未完成,即在选择裁剪区域时绘制虚线矩形,如:

strokeRect(x, y, width, height)

如何绘制虚线矩形?

3 个答案:

答案 0 :(得分:11)

这已添加到画布规范中,并非所有浏览器都已实现它,但现在是。

context.setLineDash([6]);
context.strokeRect(0, 0, 50, 50);

答案 1 :(得分:2)

虚线没有内置功能,但这是使用自定义JS原型的示例:

HTML5 Canvas and Dashed Lines

答案 2 :(得分:1)

参考:dotted stroke in <canvas>

 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;
        this.moveTo(x, y);
        var dx = (x2-x), dy = (y2-y);
        var slope = dy/dx;
        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) );
          x += xStep
          y += slope*xStep;
          this[draw ? 'lineTo' : 'moveTo'](x,y);
          distRemaining -= dashLength;
          draw = !draw;
        }
      }
    }