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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8677547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:11:57  来源:igfitidea点击:

How to draw a dashed line rectangle in canvas?

javascripthtmlhtml5-canvas

提问by user1070642

I'm tasked to do cropping in canvas and i'm finished with all the logic but one requirement is yet to be finished i.e to draw a dashed rectangle while selecting cropping area like:

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

strokeRect(x, y, width, height)

How can I draw a dashed rectangle?

如何绘制虚线矩形?

回答by Paul Milham

This has been added to the canvas spec, not all browsers have implemented it yet, but here it is.

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

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

回答by Clay Garrett

There's no built in functionality for dashed lines, but here's an example using a custom JS prototype:

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

HTML5 Canvas and Dashed Lines

HTML5 画布和虚线

回答by Clay Garrett

Refer : dotted stroke in <canvas>

参考:<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;
        }
      }
    }