我想不可能设置像 CSS 这样很容易的笔画属性。在 CSS 中,我们有虚线、点线、实线,但在 Canvas 上绘制线条/或笔划时,这似乎不是一个选项。你是如何实现的?
我看过一些例子,但对于这样一个愚蠢的函数来说,它们真的很长。
例如:
最佳答案
有趣的问题!我已经编写了虚线的自定义实现;你可以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,150
到 170,10
的线,虚线长度为 30 像素,间隔为 10 像素,您可以使用:
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
的“非常短”破折号长度与圆 Angular lineCap 相结合会在您的线上形成点。
如果有人知道访问 Canvas 上下文路径的当前点的方法,我很想知道它,因为它可以让我将其写为 ctx.dashTo(x, y,dashes)
而不是要求您在方法调用中重新指定起点。
关于javascript - <canvas> 中的虚线描边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4576724/