在jsPDF中创建虚线或点线

11
2个回答

13

我曾经遇到过同样的问题,解决方法如下:

/**
 * 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;
    }
}

10

jsPDF的最新版本已经内置了一个函数:

setLineDash 【文档】

例如以下代码绘制了一条由连续10mm的线段和10mm的空白段交替组成的虚线,并沿左到右方向重复。假设你正在绘制的页面具有默认设置(即A4纸张,毫米单位等):

doc.setLineDash([10, 10], 0);
doc.line(20, 25, 60, 25);

在此输入图片描述

下面的线条将绘制7毫米的实线,3毫米的空格,1毫米的实线,3毫米的空格,然后重复这个过程。不过,它会从10毫米处开始图案,所以第一个要绘制的破折号部分是1毫米长的那一段:

doc.setLineDash([7, 3, 1, 3], 10);
doc.line(20, 25, 60, 25);

输入图片说明


1
我为什么不能在Angular中使用这个方法?jspdf中不存在,为什么? - Morteza Fathnia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接