Search code examples
javascripthtmlcssgame-developmenttile

How can I cut an image into isometric individual tiles using javascript and canvas?


can anyone help me with this one... Ive been stuck with this issue for a couple of weeks now... In theory any image should work for this, I can upload one if required, but basically it's an isometric rendered map from Blender... Originally looking at this question from stackoverflow: Cutting an Image into pieces through Javascript

But my needs are a bit different because I intend to cut a whole map with isometric tiles, I have achieved a good projection formula, but can't seem to apply it properly to my canvas cut function, this is my current snippet:

var tileWidth = 256;
var tileHeight = 256;
var totalColumns = 30;
var totalRows = 30;
var isometric = true
var isoOffsetX = 14;
var isoOffsetY = 2;
var isoSpacing = 12;
var image = new Image();
var renderDiv = document.getElementById("render");

image.onload = cutImageUp;
image.src = './test.jpeg';

function cutImageUp() {
    var imagePieces = [];
    for(var x = 0; x < totalColumns; ++x) {
        for(var y = 0; y < totalRows; ++y) {
            var canvas = document.createElement('canvas');
            canvas.width = tileWidth;
            canvas.height = tileHeight;
            var context = canvas.getContext('2d');
            var tileX = x * tileWidth;
            var tileY = y * tileHeight;

            if (isometric){
              // tileX = (a - b + isoOffsetX) * (tileSize.x / 2 + isoSpacing)
              // tileY = (a + b + isoOffsetY) * (tileSize.x / 4 + isoSpacing)
            }

            context.drawImage(image, tileX, tileY, tileWidth, tileHeight, 0, 0, canvas.width, canvas.height);
            imagePieces.push(canvas.toDataURL());
        }
    }
    var imageElement = document.createElement("img");
    imageElement.src = imagePieces[0];
    renderDiv.appendChild(imageElement);
}
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>split image into tiles</title>
  <!-- <link rel="stylesheet" href="./style.css"> -->

</head>
<body>
<div id="render"></div>
<canvas id="canvas"></canvas>
<script  src="./script.js"></script>


</body>
</html>

I really appreciate all help I can get, thanks in advance!


Solution

  • Cut single tiles with bounding box and remove the corner triangles.

    Use context.globalCompositeOperation=destination-out to draw "transparent" triangles where you want to remove https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation

    Otherwise, it's easier to process your tiles when they are already separated:

    enter image description here