Jig*_*iya 43
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.setLineDash([5, 3]);/*dashes are 5px and spaces are 3px*/
ctx.beginPath();
ctx.moveTo(0,100);
ctx.lineTo(400, 100);
ctx.stroke();
Run Code Online (Sandbox Code Playgroud)
Ric*_*ard 16
仅供参考 - 虚线和虚线是现在在规范中的一些新画布功能的一部分 - 并且已在Chrome中实现:
http://www.rgraph.net/blog/2013/january/html5-canvas-dashed-lines.html
API*_*API 16
这是创建虚线的更简单方法:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.setLineDash([5, 15]);
ctx.beginPath();
ctx.moveTo(0,100);
ctx.lineTo(400, 100);
ctx.stroke();
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
您可以使用该setLineDash()方法.
context.setLineDash([2,3]);
Run Code Online (Sandbox Code Playgroud)
http://www.rgraph.net/blog/2013/january/html5-canvas-dashed-lines.html
在画布上绘制虚线
我提供的并不是一个完整的解决方案,而是一种在任意两点之间绘制虚线(任何角度的线)的简单方法。它画得非常快。
您可以对其进行修改以满足您对虚线的需求。绘制破折号不应明显减慢绘制速度。
这是代码和小提琴:http ://jsfiddle.net/m1erickson/pW4De/
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
DrawDottedLine(300,400,7,7,7,20,"green");
function DrawDottedLine(x1,y1,x2,y2,dotRadius,dotCount,dotColor){
var dx=x2-x1;
var dy=y2-y1;
var spaceX=dx/(dotCount-1);
var spaceY=dy/(dotCount-1);
var newX=x1;
var newY=y1;
for (var i=0;i<dotCount;i++){
drawDot(newX,newY,dotRadius,dotColor);
newX+=spaceX;
newY+=spaceY;
}
drawDot(x1,y1,3,"red");
drawDot(x2,y2,3,"red");
}
function drawDot(x,y,dotRadius,dotColor){
ctx.beginPath();
ctx.arc(x,y, dotRadius, 0, 2 * Math.PI, false);
ctx.fillStyle = dotColor;
ctx.fill();
}
Run Code Online (Sandbox Code Playgroud)