图形对象无法渲染旋转图像?波函数坍缩算法开发问题
波函数坍缩算法中旋转后的Tile图像无法渲染
我正在开发波函数坍缩算法,现有一个包含image对象的Tile类。当某个条件不满足时,我会创建新的Tile实例,使用原图像并旋转指定角度,但旋转后的图像无法在graphics对象中渲染。我有两张基础图像(空白图和向上图),其中向上图需要生成3种旋转变体(向右、向下、向左)。
当前旋转图像的代码
getImageRotate(numRotate) { let newImg = {}; newImg = createGraphics(this.W, this.H); newImg.imageMode(CENTER); newImg.translate(this.W / 2, this.H / 2); newImg.rotate(HALF_PI * numRotate); newImg.image(this.IMG, 0, 0); return newImg; }
当前渲染效果:旋转后的图像无法显示,仅能看到空白或未渲染的单元格。
测试用三角形渲染代码(可正常工作)
将代码修改为绘制三角形后,graphics对象能正常渲染,说明仅图像渲染存在问题:
getImageRotate(numRotate) { let newImg = {}; newImg = createGraphics(this.W, this.H); newImg.imageMode(CENTER); newImg.translate(this.W / 2, this.H / 2); newImg.rotate(HALF_PI * numRotate); newImg.background(0); newImg.triangle(-20, 0, 20, 0, 0, 20); return newImg; }
此代码可正常渲染出旋转后的三角形。
Preload阶段代码
function preload() { /* SETUP VARIABLES */ const PATH = "images/"; const EXT = ".png"; const NUM_IMG = 2; const DIM = createVector(100, 100); let img = {}; let tileIndx = 0; for (let i = 0; i < NUM_IMG; i++) { img = loadImage(`${PATH}${i}${EXT}`); tiles[tileIndx] = new Tile(img, EDGES[i], DIM.x, DIM.y); addRotationVarients(); tileIndx++; } function addRotationVarients() { const ORIGINAL_TILE = tiles[tileIndx]; let newEdges = {}; let newImg = {}; for (let numRotate = 1; numRotate < 4; numRotate++) { newEdges = ORIGINAL_TILE.getEdgeRotate(numRotate); if (!arrayEqual(ORIGINAL_TILE.EDGES, newEdges)) { newImg = ORIGINAL_TILE.getImageRotate(numRotate); tileIndx++; tiles[tileIndx] = new Tile(newImg, newEdges, DIM); } } } function arrayEqual(arr1, arr2) { if (arr1.length != arr2.length) { return false; } for (let n = 0; n < arr1.length; n++) { if (arr1[n] != arr2[n]) { return false; } } return true; } }
网格绘制代码
function drawGrid() { const W = canvasWidth / DIM; const H = canvasHeight / DIM; for (let r = 0; r < DIM; r++) { for (let c = 0; c < DIM; c++) { const INDX = r + c * DIM; const CELL = this.grid[INDX]; if (CELL.isCollapsed) { try { image(tiles[CELL.options[0]].img, c * W, r * H, W, H); } catch (ERR) { console.log(ERR); } } else { push(); stroke(255, 100); fill(0); rect(c * W, r * H, W, H); pop(); } } } }
预期效果与已尝试方案
预期效果:参考某视频41:13处的渲染效果,所有旋转后的Tile图像都能正常显示在网格中。
已尝试:
- 在preload()中提前旋转图像,无效
- 在draw()中实时旋转图像,虽然有效但不符合程序逻辑,且会消耗大量计算资源
寻求在preload阶段生成旋转后的Tile图像并能正常渲染的解决方案。
内容的提问来源于stack exchange,提问作者Not A Good Programmer
相关产品推荐
相关产品推荐

