javascript 在jsPDF中创建虚线或虚线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27760789/
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
Create a dashed or dotted line in jsPDF
提问by Uncoke
I need to draw a dashed line in a PDF created using jsPDF (https://mrrio.github.io/jsPDF/doc/symbols/jsPDF.html)
我需要在使用 jsPDF ( https://mrrio.github.io/jsPDF/doc/symbols/jsPDF.html)创建的 PDF 中绘制一条虚线
A simple line is created as:
一个简单的线被创建为:
doc.line(20, 25, 60, 25);
How can I create a dashed or dotted line ?
如何创建虚线或虚线?
回答by Florian Müller
I had the same problem, and did it like so:
我遇到了同样的问题,并且这样做了:
/**
* Draws a dotted line on a jsPDF doc between two points.
* Note that the segment length is adjusted a little so
* that we end the line with a drawn segment and don't
* overflow.
*/
function dottedLine(doc, xFrom, yFrom, xTo, yTo, segmentLength)
{
// Calculate line length (c)
var a = Math.abs(xTo - xFrom);
var b = Math.abs(yTo - yFrom);
var c = Math.sqrt(Math.pow(a,2) + Math.pow(b,2));
// Make sure we have an odd number of line segments (drawn or blank)
// to fit it nicely
var fractions = c / segmentLength;
var adjustedSegmentLength = (Math.floor(fractions) % 2 === 0) ? (c / Math.ceil(fractions)) : (c / Math.floor(fractions));
// Calculate x, y deltas per segment
var deltaX = adjustedSegmentLength * (a / c);
var deltaY = adjustedSegmentLength * (b / c);
var curX = xFrom, curY = yFrom;
while (curX <= xTo && curY <= yTo)
{
doc.line(curX, curY, curX + deltaX, curY + deltaY);
curX += 2*deltaX;
curY += 2*deltaY;
}
}
回答by Todd
Later versions of jsPDF
have a built-in function:
更高版本的jsPDF
有一个内置函数:
setLineDash
[Docs]
setLineDash
[文档]
The following, for example, draws a dashed line consiting of 10mm of line drawn, followed by 10mm of space repeating along the way from left to right. I've assumed you're drawing onto a page that has all the default settings (i.e. A4, mm units, etc):
例如,下面绘制一条由 10 毫米长的线组成的虚线,然后是 10 毫米的空间,从左到右重复。我假设您要在具有所有默认设置(即 A4、毫米单位等)的页面上绘图:
doc.setLineDash([10, 10], 0);
doc.line(20, 25, 60, 25);
And the below will draw 7mm of line, 3mm of space, 1mm of line, 3mm of space and then repeats, however, it will start the pattern 10mm in so the first part of the dash to be drawn is the 1mm section:
下面将绘制 7mm 的线,3mm 的空间,1mm 的线,3mm 的空间,然后重复,但是,它将在 10mm 处开始图案,因此要绘制的破折号的第一部分是 1mm 部分:
doc.setLineDash([7, 3, 1, 3], 10);
doc.line(20, 25, 60, 25);