【发布时间】:2021-03-30 15:41:57
【问题描述】:
所以,我正在尝试使用箭头键让角色在屏幕上移动,虽然它有效,但它会留下条纹。我不希望我的后端出现条纹。我知道它为什么会出现这些条纹,但不知道如何摆脱它们。条纹的原因是玩家正在从画布中清除,然后以很大的延迟进行渲染。我该如何阻止它?
编辑:我希望它只清除播放器,周围什么都没有。
片段:
const c = document.getElementById('c')
const ctx = c.getContext('2d')
c.height = window.innerHeight
c.width = window.innerWidth
let blockInfo = {
h: 15, // Height in pixels. I'm gonna use this like blocks, like this: blockAmount * blockInfo.h
w: 15
}
let renderedPlayer = false // The player wasn't rendered yet so this is false
let player = {
speed: 0.125,
x: 2,
y: 2,
height: 1,
width: 1
}
function clearPlayer() { // I think this is where the glitch comes in.
ctx.clearRect(player.x * blockInfo.w, player.y * blockInfo.h, player.width * blockInfo.w, player.height * blockInfo.h)
}
function renderPlayer() {
ctx.fillRect(player.x * blockInfo.w, player.y * blockInfo.h, player.width * blockInfo.w, player.height * blockInfo.h)
}
function press(e) { // When a character on the keyboard gets pressed:
let w = e.which
if (renderedPlayer == true) {
clearPlayer() // It clears the player before the player moves, so it doesn't have more streaks.
if (w == 39) {
player.x += player.speed
} else if (w == 37) {
player.x -= player.speed
} else if (w == 38) {
player.y -= player.speed
} else if (w == 40) {
player.y += player.speed
}
}
}
setInterval(function() { // Rendering player each MS.
renderedPlayer = false
renderPlayer()
renderedPlayer = true
}, 0)
body {
margin: 0;
overflow: hidden;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body onkeydown="press(event)">
<canvas id="c"></canvas>
<script src="script.js"></script>
</body>
</html>
【问题讨论】:
-
在每一帧开始时清除整个画布。当您开始拥有许多移动物体时,很难清除它们。
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height)非常非常快。也使用requestAnimartionFramedeveloper.mozilla.org/en-US/docs/Web/API/window/… 而不是走内存泄漏setInterval -
这会有所帮助,但您可以将其作为答案而不是评论。不过,还是谢谢你的教导。
标签: javascript html css html5-canvas