0

I use Scala for various home projects and I've run into one that involves simple canvas drawing, with a few basic input controls like buttons and text boxes. I'm aware of how to use Swing, but I'm starting to wonder if I'm wasting my time learning this technology. What is the simplest way to draw on an HTML 5 canvas in Scala, perhaps adding a few button controls for input.. is this where I need to begin learning the Play framework? Does anything out there abstract away from HTML/Javascript (I do not know either well.)

I don't understand what the official Scala strategy is for this kind of input/output moving forward, since the Swing library is heading for retirement. I'd like to sharpen my skills in the right direction, if I better knew what that was.

Thank you

1 Answer 1

2

You should consider Scala.js, the Scala to JavaScript compiler. It compiles your Scala code to JavaScript, so you can run it directly in the browser.

Scala-Js-Fiddle is a great way to try this out in your browser.

You could for example do the following (assuming you have the DOM library on the classpath):

import org.scalajs.dom
import org.scalajs.dom.html

import scala.scalajs.js

object CanvasExample extends js.JSApp {
  def main(): Unit = {
    val canvas = dom.document
                   .getElementById("myCanvas")
                   .asInstanceOf[html.Canvas]
    val ctx = canvas.getContext("2d")
                .asInstanceOf[dom.CanvasRenderingContext2D]

    ctx.fillStyle = "red"
    ctx.fillRect(0, 0, 255, 255)
  }

}

The Hands-on Scala.js book goes into further detail and has a great walk-through.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.