Last active
October 18, 2023 09:30
-
-
Save tnolet/6915614 to your computer and use it in GitHub Desktop.
An isometric grid based on SVG rectangles. The isometry is generated through an matrix translation. Not ideal, but pretty quick....
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>D3 iso test grid</title> | |
<link rel="stylesheet" href="css/iso_grid.css"> | |
<script src="d3/d3.v3.min.js" charset="utf-8"></script> | |
<script src="jquery/jquery-1.10.2.min.js" charset="utf-8"></script> | |
</head> | |
<body> | |
<div id="D3rects" class="container" > | |
<script> | |
// Select the DIV container "D3line" then | |
// add an SVG element to it | |
var viewWidth = 600; | |
var viewHeight = 600; | |
var gridSize = 6; // The amount of tiles on the x and y axis | |
var gridWidth = ((viewWidth - gridSize) / gridSize); // The gridWidth takes into account the width and height of the | |
var gridHeight = ((viewHeight - gridSize) / gridSize); // view. Note: if tile1 is 40px wide, the next tile should start at 41px | |
$(D3rects).css('width',(viewWidth + viewWidth)); // set the size of the div | |
$(D3rects).css('height',(viewHeight)); | |
var rectGrid = d3.select("#D3rects") | |
.append("svg:svg") | |
.attr("width", viewWidth + viewWidth) | |
.attr("height", viewHeight) | |
// .attr("viewBox", "0,0," + viewWidth + "," + viewHeight + "") | |
.attr("preserveAspectRatio", "xMidYMin") | |
.append("g") | |
.attr("transform","matrix(1,-.5,1,.5,0," + (viewHeight /2) + ")"); | |
for (var i=0; i <= (gridSize-1); i++){ | |
for (var j=0; j <= (gridSize-1); j++) { | |
rectGrid.append("svg:rect") | |
.attr("x", (i * gridWidth) + i) //add j and i to make sure stuff doesn't overlap | |
.attr("y", (j * gridHeight)+ j) | |
.attr("rx", 2) | |
.attr("ry", 2) | |
.attr("width", gridWidth) | |
.attr("height", gridHeight) | |
.attr("class", "gridTile"); | |
rectGrid.append("text") | |
.attr("x", (i * gridWidth) + i + (gridWidth/2)) | |
.attr("y", (j * gridHeight) + j +(gridHeight/2)) | |
.text(i + " , " + j) | |
.attr("class", "gridTileText") | |
.attr("text-anchor","middle"); | |
}; | |
}; | |
var isoToScreen = function(x, y) { | |
var posX = (x - y) * gridWidth; | |
var posY = (x + y) * gridHeight / 2; | |
return [posX, posY]; | |
}; | |
var screenToIso = function(screenX, screenY) | |
{ | |
var isoX = screenY / tileH + screenX / (2*tileW) | |
var isoY = screenY / tileH - screenX / (2*tileW) | |
return [isoX, isoY]; | |
} | |
</script> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment