Skip to content

Instantly share code, notes, and snippets.

@orllewin
Created March 13, 2022 19:11
Show Gist options
  • Select an option

  • Save orllewin/465efd18a3e8351e2681592939e31453 to your computer and use it in GitHub Desktop.

Select an option

Save orllewin/465efd18a3e8351e2681592939e31453 to your computer and use it in GitHub Desktop.
Basic gameloop in Kotlin JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Client</title>
</head>
<body>
<div id="root">
<canvas id="lluniaucanvas" width="200" height="200" style="border:1px solid">
Your browser does not support the canvas tag.
</canvas>
</div>
<script src="LluniauWeb.js"></script>
</body>
</html>
import kotlinx.browser.document
import kotlinx.browser.window
import org.w3c.dom.CanvasRenderingContext2D
import org.w3c.dom.HTMLCanvasElement
import kotlin.random.Random
lateinit var context: CanvasRenderingContext2D
lateinit var canvas: HTMLCanvasElement
fun main() {
console.log("LluniauWeb")
canvas = document.getElementById("lluniaucanvas") as HTMLCanvasElement
context = canvas.getContext("2d") as CanvasRenderingContext2D
window.requestAnimationFrame { timestamp ->
draw()
loop(timestamp)
}
}
private fun loop(timestamp: Double){
window.requestAnimationFrame { timestamp ->
draw()
loop(timestamp)
}
}
private fun draw(){
context.clearRect(0.0, 0.0, canvas.width.toDouble(), canvas.height.toDouble())
context.strokeStyle = "#000000"
context.stroke()
context.beginPath()
context.moveTo(random(context.canvas.width).toDouble(), 0.0)
context.lineTo(random(context.canvas.width).toDouble(), context.canvas.height.toDouble())
context.closePath()
}
private fun random(max: Int): Int = Random.nextInt(max)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment