Skip to content

Instantly share code, notes, and snippets.

@JoeCrash
Last active December 9, 2020 19:10
Show Gist options
  • Save JoeCrash/cf2223d40fd6c0f033bf81b190a67e7f to your computer and use it in GitHub Desktop.
Save JoeCrash/cf2223d40fd6c0f033bf81b190a67e7f to your computer and use it in GitHub Desktop.
Pixi.js 5 - Draw Dashed Lines using dash/gap points
PIXI.Graphics.prototype.drawDashLine = function(toX, toY, dash = 7, gap = 3) {
//TYPE B. actual points
const lastPos = this.currentPath.points;
let ax = lastPos[lastPos.length - 2] || 0;
let ay = lastPos[lastPos.length - 1] || 0;
let xlen = toX - ax;
let ylen = toY - ay;
let lineLen = getDistanceBetweenPoints(ax, ay, toX, toY);
let totalDashes = lineLen / (dash + gap);
let dashes = 0;
let ratio = dash / lineLen;
let gapRatio = gap / lineLen;
while(dashes < totalDashes){
let endX = ax + xlen * ratio;
let endY = ay + ylen * ratio;
this.moveTo(ax, ay); //move to dash start
this.lineTo(endX, endY); //do dash
ax = endX + xlen * gapRatio; //get new x,y after gap
ay = endY + ylen * gapRatio;
let distLeft = getDistanceBetweenPoints(ax, ay, toX, toY);
if(distLeft < dash+gap){
this.moveTo(ax, ay); //get to last position
this.lineTo(toX, toY); //insert a shrunken last dash and stop
break;
}
dashes++;
}
function getDistanceBetweenPoints(ax, ay, bx, by){
return Math.round(Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2)));
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment