Added basic render loop code
This commit is contained in:
parent
c38cb58b3e
commit
015faf5d40
65
src/renderLoop.html
Normal file
65
src/renderLoop.html
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
<html>
|
||||||
|
<body>
|
||||||
|
<canvas id="render" width="1920" height="1080"></canvas>
|
||||||
|
</body>
|
||||||
|
<style>
|
||||||
|
#render {
|
||||||
|
width: 100%;
|
||||||
|
aspect-ratio: 16/9;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<script>
|
||||||
|
const canvas = document.getElementById("render");
|
||||||
|
const { width, height } = canvas;
|
||||||
|
const ctx = canvas.getContext("2d");
|
||||||
|
ctx.font = "32px sans-serif";
|
||||||
|
let lastRenderTime = performance.now();
|
||||||
|
|
||||||
|
const sprites = new Image();
|
||||||
|
sprites.src =
|
||||||
|
"https://assets.pfy.ch/shipyard-icons/New_JerseyShipyardIcon.png";
|
||||||
|
let spritePos = [100, 100];
|
||||||
|
let xFlip = 1;
|
||||||
|
let yFlip = 1;
|
||||||
|
|
||||||
|
const renderFrameRate = (delta) => {
|
||||||
|
const fps = 1 / (delta / 1000);
|
||||||
|
|
||||||
|
ctx.fillStyle = "#fff";
|
||||||
|
ctx.fillText(`${fps.toFixed()} FPS`, 10, 42);
|
||||||
|
};
|
||||||
|
|
||||||
|
const draw = (ms) => {
|
||||||
|
const delta = ms - lastRenderTime;
|
||||||
|
|
||||||
|
ctx.fillStyle = "#000";
|
||||||
|
ctx.fillRect(0, 0, width, height);
|
||||||
|
|
||||||
|
renderFrameRate(delta);
|
||||||
|
|
||||||
|
const moveDistance = 100 / delta;
|
||||||
|
|
||||||
|
spritePos[0] += moveDistance * xFlip;
|
||||||
|
spritePos[1] += moveDistance * yFlip;
|
||||||
|
|
||||||
|
if (spritePos[0] > width) {
|
||||||
|
xFlip = -1;
|
||||||
|
} else if (spritePos[0] <= 0) {
|
||||||
|
xFlip = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (spritePos[1] > height) {
|
||||||
|
yFlip = -1;
|
||||||
|
} else if (spritePos[1] <= 0) {
|
||||||
|
yFlip = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.drawImage(sprites, ...spritePos);
|
||||||
|
|
||||||
|
lastRenderTime = performance.now();
|
||||||
|
requestAnimationFrame(draw);
|
||||||
|
};
|
||||||
|
|
||||||
|
requestAnimationFrame(draw);
|
||||||
|
</script>
|
||||||
|
</html>
|
Loading…
Reference in New Issue
Block a user