let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 400;
class Map {
constructor(x, y, name) {
this.x = x;
this.y = y;
this.name = name;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 5, 0, Math.PI * 2);
ctx.fill();
ctx.font = "12px arial";
ctx.textAlign = "center";
ctx.fillText(this.name, this.x, this.y - 10);
}
}
let locations = [];
let california = locations.push(new Map(30, 200, "California"));
let oregon = locations.push(new Map(50, 100, "Oregon"));
let washington = locations.push(new Map(50, 25, "Washington"));
let nevada = locations.push(new Map(150, 180, "Nevada"));
let utah = locations.push(new Map(210, 170, "Utah"));
let arizona = locations.push(new Map(200, 230, "Arizona"));
function drawLocations() {
for (let i = 0; i < locations.length; i++) {
locations[i].draw();
}
}
drawLocations();
class Roads {
constructor(x1, y1, x2, y2, name) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.name = name;
}
draw() {
ctx.beginPath();
ctx.strokeStyle = "red";
ctx.moveTo(this.x1, this.y1);
ctx.lineTo(this.x2, this.y2);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
}
let roads = [];
let CA_OR = roads.push(
new Roads(
locations[0].x,
locations[0].y,
locations[1].x,
locations[1].y,
"HWY1"
)
);
let OR_WA = roads.push(
new Roads(
locations[1].x,
locations[1].y,
locations[2].x,
locations[2].y,
"HWY1"
)
);
let CA_NV = roads.push(
new Roads(
locations[0].x,
locations[0].y,
locations[3].x,
locations[3].y,
"I80"
)
);
let NV_UT = roads.push(
new Roads(
locations[3].x,
locations[3].y,
locations[4].x,
locations[4].y,
"I80"
)
);
let UT_CO = roads.push(
new Roads(
locations[4].x,
locations[4].y,
locations[5].x,
locations[5].y,
"I15"
)
);
function drawRoads() {
for (let i = 0; i < roads.length; i++) {
roads[i].draw();
getAngle(roads[i], roads[i].name);
}
}
drawRoads();
function drawNames(ang, x1, y1, name) {
ctx.font = "10px arial";
ctx.textAlign = "center";
ctx.save();
ctx.translate(x1, y1);
ctx.rotate(ang);
if (name == "I15") {
ctx.rotate(-ang);
}
if (name == "I80") {
ctx.fillText(name, 0, 15);
} else if (name == "I15") {
ctx.fillText(name, 15, 0);
} else {
ctx.fillText(name, 0, -5);
}
ctx.restore();
}
function getAngle(roads, name) {
let dx = roads.x1 - roads.x2;
let dy = roads.y1 - roads.y2;
let midX = roads.x1 + (roads.x2 - roads.x1) * 0.5;
let midY = roads.y1 + (roads.y2 - roads.y1) * 0.5;
drawNames(Math.atan2(-dy, -dx), midX, midY, name);
}
<canvas id="canvas"></canvas>