gpt4 book ai didi

javascript - 背景图片翻译?

转载 作者:行者123 更新时间:2023-11-30 17:48:47 27 4
gpt4 key购买 nike

我正在尝试在 Canvas 中向下移动基本的横向滚动条,并且我对移动本身处于一个很好的位置,但我似乎无法转换背景。也许我误解了翻译的工作原理?主 Canvas 翻译良好(“玩家”所在的 Canvas )但背景 Canvas 不会移动。

http://jsfiddle.net/Y5SG8/1/

全屏:http://jsfiddle.net/Y5SG8/1/embedded/result/

如有任何帮助,我们将不胜感激。

(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();

var canvas = document.getElementById('canvas'),
bg = document.getElementById('canvas2'),
ctx = canvas.getContext('2d'),
bgctx = bg.getContext('2d'),
width = 1280,
height = 720,
player = {
x: width/2,
y: height/2 - 15,
width: 16,
height: 24,
speed: 3,
velx: 0,
vely: 0,
jumping: false
},

keys = [],
friction = 0.9,
gravity = 0.3;

canvas.addEventListener('keydown', function(e) {keys[e.keyCode] = true;})
canvas.addEventListener('keyup', function(e) {keys[e.keyCode] = false;})

canvas.width = width;
canvas.height = height;
bg.width = width;
bg.height = height;

var bgimg = new Image();
bgimg.src = 'bg.png';

bgimg.onload = function bgload() {bgctx.drawImage(bgimg,0,0);}

function playerupdate() {

if (keys[68]) {
if (player.velx < player.speed) {player.velx++;}
}
if (keys[65]) {
if (player.velx > -player.speed) {player.velx--;}
}

player.velx *= friction;

player.x += player.velx;
ctx.translate(-player.velx,0);
bgctx.translate(player.velx,0);


ctx.clearRect(player.x, player.y, player.width, player.height);
ctx.fillStyle = '#FF0000'
ctx.fillRect(player.x, player.y, player.width, player.height);


requestAnimationFrame(playerupdate);

console.log(player.x)

}

window.onload = playerupdate();

最佳答案

简而言之,translate 函数会翻译 Canvas 的上下文,但不会重绘,因此您需要:

// note you probably want the ctx to translate in the opposite direction of 
// the player's velocity if you want the appearance of movement (if that's
// what you want)
bgctx.translate(-player.velx, 0);
bgctx.clearRect(0, 0, bg.width, bg.height);
bgctx.drawImage(bgimg, 0, 0);

知道了这一点,您可能可以从那里弄清楚。如果您的背景是非重复的(并且您阻止玩家离开边缘),那么这可能是解决方案。

如果您的背景是可重复的,您需要做更多的工作,因为转换图像会很快将其移出屏幕。您可以通过绘制从图像创建的重复填充来解决此问题,而不是在图像本身中绘制,例如:

// on image load, replacing your initial `drawImage`
bgimg.onload = function bgload() {
var ptrn = bgctx.createPattern(bgimg, 'repeat');
bgctx.fillStyle = ptrn;
bgctx.fillRect(0, 0, bg.width, bg.height);
}

// then in the loop
bgctx.translate(-player.velx, 0);
// Here you'd fill a square *around* the player, instead of just
// repainting the image.
bgctx.fillRect(player.x - width/2, 0, bg.width, bg.height);

关于javascript - 背景图片翻译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19543794/

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