【发布时间】:2016-05-04 08:36:31
【问题描述】:
我正在画布上绘制一个基于六边形的网格。
每个六边形都是一个对象,其中包含 x/y 坐标中的 6 个点。 每个六边形对象还保存其 X/Y 列/行索引。
var canvas = document.getElementById("can");
canvas.width = 200;
canvas.height = 200;
var ctx = canvas.getContext("2d");
var grid = []; // array that holds the Hex
var globalOffset = 30 // not important, just for smoother display atm
function Point(x, y) {
this.x = x;
this.y = y;
}
function Hex(x, y, size) {
this.size = 20;
this.x = x;
this.y = y;
this.points = [];
this.id = [];
this.create = function(x, y) {
var offSetX = (size / 2 * x) * -1
var offSetY = 0;
if (x % 2 == 1) {
offSetY = Math.sqrt(3) / 2 * this.size;
}
var center = new Point(
x * this.size * 2 + offSetX + globalOffset,
y * Math.sqrt(3) / 2 * this.size * 2 + offSetY + globalOffset
)
this.midPoint = center;
this.id[0] = x;
this.id[1] = y;
for (var i = 0; i < 6; i++) {
var degree = 60 * i;
var radian = Math.PI / 180 * degree;
var point = new Point(
center.x + size * Math.cos(radian),
center.y + size * Math.sin(radian)
)
this.points.push(point);
}
}
this.create(x, y);
}
}
//Determine where was clicked
canvas.addEventListener("click", function(e) {
var rect = canvas.getBoundingClientRect();
var pos = {
x: e.clientX - rect.left,
y: e.clientY - rect.top
}
document.getElementById("pos").innerHTML = "click on: " + pos.x + " " + pos.y;
});
// Creating Hexagons, setting up their center point, pushing them into Grid.
function init() {
for (var i = 0; i < 5; i++) {
for (var j = 0; j < 4; j++) {
var hex = new Hex(i, j, 20);
grid.push(hex)
}
}
//for each Hex in Grid, draw the Hex
for (var hex in grid) {
var item = grid[hex];
ctx.beginPath();
ctx.moveTo(item.points[0].x, item.points[0].y);
for (var k = 1; k < item.points.length; k++) {
ctx.lineTo(item.points[k].x, item.points[k].y);
}
ctx.closePath();
ctx.stroke();
var text = item.id;
ctx.fillStyle = "black";
ctx.fillText(text, item.midPoint.x - 7, item.midPoint.y - item.size / 2.2);
}
点击画布时,我想确定我是否点击了一个十六进制,如果我点击了,是哪个十六进制(按列/行)。 它的数学问题。
我该怎么做?
【问题讨论】:
-
这里有很多jex网格的线索:redblobgames.com/grids/hexagons
标签: javascript html math canvas hexagonal-tiles