summaryrefslogtreecommitdiff
path: root/example/src/main/scala/example/ScalaJSExample.scala
blob: 7a41c44ccc599583a9e833bd66918c67b06b55e2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package example
import scala.scalajs.js.annotation.JSExport
import org.scalajs.dom
import scala.util.Random

case class Point(x: Int, y: Int){
  def +(p: Point) = Point(x + p.x, y + p.y)
  def /(d: Int) = Point(x / d, y / d)
}
// Seems like you need this for sbt ~fastOptJS to work
// mkdir ~/.sbt/0.13/plugins/target/scala-2.10/sbt-0.13/classes
@JSExport
object ScalaJSExample {
  val ctx = dom.document
    .getElementById("canvas")
    .asInstanceOf[dom.HTMLCanvasElement]
    .getContext("2d")
    .asInstanceOf[dom.CanvasRenderingContext2D]

  var count = 0
  var p = Point(0, 0)
  val corners = Seq(Point(255, 255), Point(0, 255), Point(128, 0))

  def clear() = {
    ctx.fillStyle = "white"
    ctx.fillRect(0, 0, 255, 255)
  }

  def run = for (i <- 0 until 10){
    if (count % 30000 == 0) clear()
    count += 1
    p = (p + corners(Random.nextInt(3))) / 2
    val height = 512.0 / (255 + p.y)
    val r = (p.x * height).toInt
    val g = ((255-p.x) * height).toInt
    val b = p.y
    ctx.fillStyle = s"rgb($g, $r, $b)"

    ctx.fillRect(p.x, p.y, 1, 1)
  }
  @JSExport
  def main(): Unit = {
    dom.console.log("main")

    dom.setInterval(() => run, 50)
  }
}