我正试图在画布上放下基本的侧卷轴运动,而且我在运动本身就处于一个好位置,但我似乎无法获得翻译的背景。也许我误解了翻译是如何工作的?主画布正在精细翻译(“播放器”正在播放),但bg画布不会让步。
全屏: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();
答案 0 :(得分:1)
简短回答,translate
函数会转换画布的上下文,但不会重绘,因此您需要:
// 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);
答案 1 :(得分:1)
正如@ numbers1311407在回答中所说,你需要重新绘制图像。
但这里严格来说不需要翻译 - 只需将图像重新绘制到新位置。
bgctx.drawImage(bgimg, -player.velx, 0);
<强> Modified fiddle 强>
你甚至不需要使用clear,因为图像会透支任何东西 - 你唯一需要注意的是当图像超出“束缚”时包裹/平铺或者你会撕裂(这适用于两种方法)。