gpt4 book ai didi

javascript - 重绘 Canvas html5而不闪烁

转载 作者:太空狗 更新时间:2023-10-29 14:58:34 25 4
gpt4 key购买 nike

我的屏幕每 25 毫秒重绘一次,图像闪烁,这是我的代码

                var FRAME_RATE = 40;
var intervalTime = 1000/FRAME_RATE;
gameLoop();

function gameLoop(){
context.clearRect(0, 0, 640, 640);
renderMap();
window.setTimeout(gameLoop, intervalTime);
}

这里是 renderMap() 函数

function renderMap(){
var startX = playerX - (screenW / 2);
var startY = playerY - (screenH / 2);

maxX = playerX + (screenW / 2);
maxY = playerY + (screenH / 2);
$.getJSON('mapa3.json', function(json){
for (x = startX; x < maxX; x=x+32){
for (y = startY; y < maxY; y=y+32){
intTile = json.layers[0].data[((y/32)* 100) + (x/32)];
context.putImageData(getTile(intTile - 1), x - startX, y - startY);
}
}
});

var imgCharacter = new Image();
imgCharacter.src = 'char.png';

var posX = (screenW - imgCharacter.width) / 2;
var posY = (screenH - imgCharacter.height) / 2;
imgCharacter.onload = function(){context.drawImage(imgCharacter, posX, posY)}
}

我需要对代码进行哪些更改才能停止闪烁?

最佳答案

我相信这是因为您每次迭代都在加载图像。尝试将 var imgCharacter...、下一行和图像的 onload 函数放在 renderMap 之外,这样它只运行一次

var imgCharacter = new Image();    
imgCharacter.onload = function () {
renderMap();
}
imgCharacter.src = 'char.png';

function renderMap() {
var startX = playerX - (screenW / 2);
var startY = playerY - (screenH / 2);

maxX = playerX + (screenW / 2);
maxY = playerY + (screenH / 2);
$.getJSON('mapa3.json', function (json) {
for (x = startX; x < maxX; x = x + 32) {
for (y = startY; y < maxY; y = y + 32) {
intTile = json.layers[0].data[((y / 32) * 100) + (x / 32)];
context.putImageData(getTile(intTile - 1), x - startX, y - startY);
}
}
});

var posX = (screenW - imgCharacter.width) / 2;
var posY = (screenH - imgCharacter.height) / 2;

context.drawImage(imgCharacter, posX, posY)
}

感谢markE让我知道onload函数也需要在renderMap之外,我第一次忽略了

关于javascript - 重绘 Canvas html5而不闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18423950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com