概述
晚上闲来无事,又不想看书,就写代码段锻炼一下脑子。本示例实现canva绘制虚线,因为canvas原生没有的。
效果
实现
代码语言:javascript复制function drawDashLine(start, end, dash) {
var deltX = end[0] - start[0];
var deltY = end[1] - start[1];
var totalDis = Math.sqrt(deltX * deltX deltY * deltY);
var getPos = function (pos, dis) {
var deltXS = pos[0] - start[0];
var deltYS = pos[1] - start[1];
var baseDis = Math.sqrt(deltXS * deltXS deltYS * deltYS);
var percent = (dis baseDis) / totalDis;
var x = start[0] deltX * percent;
var y = start[1] deltY * percent;
return [x, y];
};
var dis = 0;
for(var i = 0; i < dash.length; i ) {
dis = dash[i];
}
var count = Math.ceil(totalDis / dis);
var _start = start.concat([]);
ctx.lineWidth = 3;
ctx.strokeStyle = 'red';
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
for (var i = 0; i < count; i ) {
for(var j = 0; j < dash.length; j ) {
if(j % 2===0) {
ctx.beginPath();
ctx.moveTo(_start[0], _start[1]);
_start = getPos(_start, dash[j]);
ctx.lineTo(_start[0], _start[1]);
ctx.stroke();
} else {
_start = getPos(_start, dash[j]);
}
}
}
}
// 调用绘制
drawDashLine([10, 10], [500, 500], [15, 10, 1, 10]);