我使用以下代码绘制一 strip 箭头的线。 我的问题是我想要虚线而不是箭头顶部:
function canvas_arrow_alternate2(context, fromx, fromy, tox, toy){
var headlen = 12; // length of head in pixels
var angle = Math.atan2(toy-fromy,tox-fromx);
context.setLineDash([10]);
context.moveTo(fromx, fromy);
context.lineTo(tox, toy);
context.setLineDash([0]);
context.lineTo(tox-headlen*Math.cos(angle-Math.PI/6),toy-headlen*Math.sin(angle-Math.PI/6));
context.moveTo(tox, toy);
context.lineTo(tox-headlen*Math.cos(angle+Math.PI/6),toy-headlen*Math.sin(angle+Math.PI/6));
}
现在的输出是一个非虚线的箭头。 问题是“setLineDash”的更改。 我怎么能这么说
context.moveTo(fromx, fromy);
context.lineTo(tox, toy);
使用
context.setLineDash([10]);
后来的代码不是吗?
谢谢
最佳答案
您无法定义具有该精度级别的路径:当您填充或描边时,当前设置(描边样式、填充样式、fillText/描边文本即时函数的字体、lineDash、globalAlpha...)将用于绘制所有内容自上次 beginPath() 以来构建的子路径。
因此,例如,您无法构建一条黄-红-蓝-...线,具有多个 lineTo 并更改描边样式,然后立即对其进行描边():它将使用您设置的最后一个颜色进行绘制。
因此,在您的情况下,您必须分两次绘制箭头:下面的(未经测试的)代码有望帮助您找到一种方法:
function canvas_arrow_alternate2(context, fromx, fromy, tox, toy, strokeStyle){
var headlen = 12; // length of head in pixels
var angle = Math.atan2(toy-fromy,tox-fromx);
context.save();
context.strokeStyle=strokeStyle || '#000'; // defaults to black
// dashed part
context.beginPath();
context.setLineDash([10]);
context.moveTo(fromx, fromy);
context.lineTo(tox, toy);
context.stroke();
// second part -non dashed-
context.beginPath();
context.setLineDash([0]);
context.moveTo(tox, toy);
context.lineTo(tox-headlen*Math.cos(angle-Math.PI/6),toy-headlen*Math.sin(angle-Math.PI/6));
context.moveTo(tox, toy);
context.lineTo(tox-headlen*Math.cos(angle+Math.PI/6),toy-headlen*Math.sin(angle+Math.PI/6));
context.stroke();
//
context.restore(); // this will, in fact, restore strokeStyle
}
// notice you can get rid of save/restore if all your drawing methods sets the color before drawing.
确保(也许你这样做)使用 beginPath() 开始...好吧...每个新路径,否则所有绘制命令将堆积起来,并且所有绘制命令都会在每个描边()或填充()上执行,导致速度变慢。
关于javascript - Canvas 绘制带箭头的虚线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24563734/