如何使用JavaScript和画布将图像切割成等距的单个图块?

问题描述 投票:0回答:1

任何人都可以帮我解决这个问题……我已经被这个问题困扰了几周了……从理论上讲,任何图像都可以解决这个问题,如果需要,我可以上传一个,但是基本上是等轴测渲染图来自Blender ...最初从stackoverflow看这个问题:Cutting an Image into pieces through Javascript

但是我的需求有所不同,因为我打算用等距图块剪切整个地图,我已经获得了很好的投影公式,但是似乎无法正确地将其应用于画布剪切功能,这是我当前的代码段:

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>

我非常感谢我能获得的所有帮助,预先感谢!

javascript html css game-development tile
1个回答
0
投票

使用边界框剪切单个图块,然后删除边角三角形。

使用context.globalCompositeOperation=destination-out在要删除的位置绘制“透明”三角形https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation

否则,当您的磁贴已经分离时,处理它们会更容易:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.