<canvas> 中的虚线笔画 [英] dotted stroke in <canvas>
问题描述
我猜想设置描边属性是不可能的,比如 CSS,这很容易.使用 CSS 我们有虚线、虚线、实线,但在画布上绘制线条/或笔划时,这似乎不是一个选项.你是如何实施的?
I guess it is not possible to set stroke property such as CSS which is quite easy. With CSS we have dashed, dotted, solid but on canvas when drawing lines/or strokes this doesn't seem to be an option. How have you implemented this?
我看过一些例子,但他们真的很期待这样一个愚蠢的功能.
I've seen some examples but they are really long for such a silly function.
例如:
推荐答案
有趣的问题!我写了一个自定义的虚线实现;您可以在这里试用.我采用了 Adobe Illustrator 的路线,并允许您指定一系列短划线/间隙长度.
Fun question! I've written a custom implementation of dashed lines; you can try it out here. I took the route of Adobe Illustrator and allow you to specify an array of dash/gap lengths.
对于 stackoverflow 的后代,这是我的实现(对 s/o 线宽略有改动):
For stackoverflow posterity, here's my implementation (slightly altered for s/o line widths):
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 像素的间隙,您可以使用:
To draw a line from 20,150
to 170,10
with dashes that are 30px long followed by a gap of 10px, you would use:
myContext.dashedLine(20,150,170,10,[30,10]);
要绘制交替的破折号和点,请使用(例如):
To draw alternating dashes and dots, use (for example):
myContext.lineCap = 'round';
myContext.lineWidth = 4; // Lines 4px wide, dots of diameter 4
myContext.dashedLine(20,150,170,10,[30,10,0,10]);
0
的非常短"的破折号长度与圆形的 lineCap 相结合,会在您的线条上形成点.
The "very short" dash length of 0
combined with the rounded lineCap results in dots along your line.
如果有人知道访问画布上下文路径当前点的方法,我很想知道它,因为它允许我将其写为 ctx.dashTo(x,y,dashes)
而不是要求您在方法调用中重新指定起点.
If anyone knows of a way to access the current point of a canvas context path, I'd love to know about it, as it would allow me to write this as ctx.dashTo(x,y,dashes)
instead of requiring you to re-specify the start point in the method call.
这篇关于<canvas> 中的虚线笔画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!