71 lines
2.4 KiB
JavaScript
71 lines
2.4 KiB
JavaScript
import {FLAT, POINTY} from './consts.js';
|
|
import {range, toFixed} from './utils.js';
|
|
|
|
export default class DrawHexagon {
|
|
constructor(settings) {
|
|
this.settings = Object.assign({}, settings);
|
|
|
|
this.flatTopCornerX = [];
|
|
this.flatTopCornerY = [];
|
|
this.pointyTopCornerX = [];
|
|
this.pointyTopCornerY = [];
|
|
|
|
const hexSides = 6;
|
|
const hexSlices = 24;
|
|
|
|
range(hexSlices).forEach(hexSlice => {
|
|
const x = toFixed(Math.cos(((hexSlice / hexSlices) * hexSides) * (2 * Math.PI) / hexSides));
|
|
const y = toFixed(Math.sin(((hexSlice / hexSlices) * hexSides) * (2 * Math.PI) / hexSides));
|
|
|
|
if ((hexSlice % 4) === 0) {
|
|
const cur = hexSlice / 4;
|
|
this.flatTopCornerX[cur] = x;
|
|
this.flatTopCornerY[cur] = y;
|
|
}
|
|
|
|
if (((hexSlice-2) % 4) === 0) {
|
|
const cur = (hexSlice-2) / 4;
|
|
this.pointyTopCornerX[cur] = x;
|
|
this.pointyTopCornerY[cur] = y;
|
|
}
|
|
});
|
|
}
|
|
|
|
outline(context, scale, x, y, cell) {
|
|
scale = scale * cell.scale;
|
|
let hexCornerX = cell.orientation === POINTY ? this.pointyTopCornerX : this.flatTopCornerX;
|
|
let hexCornerY = cell.orientation === POINTY ? this.pointyTopCornerY : this.flatTopCornerY;
|
|
|
|
context.beginPath();
|
|
context.moveTo(x + scale * hexCornerX[0], y + scale * hexCornerY[0]);
|
|
context.lineTo(x + scale * hexCornerX[1], y + scale * hexCornerY[1]);
|
|
context.lineTo(x + scale * hexCornerX[2], y + scale * hexCornerY[2]);
|
|
context.lineTo(x + scale * hexCornerX[3], y + scale * hexCornerY[3]);
|
|
context.lineTo(x + scale * hexCornerX[4], y + scale * hexCornerY[4]);
|
|
context.lineTo(x + scale * hexCornerX[5], y + scale * hexCornerY[5]);
|
|
context.closePath();
|
|
|
|
context.lineWidth = cell.width;
|
|
context.strokeStyle = cell.getColor();
|
|
context.stroke();
|
|
}
|
|
|
|
fill(context, scale, x, y, cell) {
|
|
scale = scale * cell.scale;
|
|
let hexCornerX = cell.orientation === POINTY ? this.pointyTopCornerX : this.flatTopCornerX;
|
|
let hexCornerY = cell.orientation === POINTY ? this.pointyTopCornerY : this.flatTopCornerY;
|
|
|
|
context.beginPath();
|
|
context.moveTo(x + scale * hexCornerX[0], y + scale * hexCornerY[0]);
|
|
context.lineTo(x + scale * hexCornerX[1], y + scale * hexCornerY[1]);
|
|
context.lineTo(x + scale * hexCornerX[2], y + scale * hexCornerY[2]);
|
|
context.lineTo(x + scale * hexCornerX[3], y + scale * hexCornerY[3]);
|
|
context.lineTo(x + scale * hexCornerX[4], y + scale * hexCornerY[4]);
|
|
context.lineTo(x + scale * hexCornerX[5], y + scale * hexCornerY[5]);
|
|
|
|
context.fillStyle = cell.getColor();
|
|
context.fill();
|
|
}
|
|
}
|
|
|