Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 25, 2024 10:19
Show Gist options
  • Save dacr/b56441215ce3b1b8a8499a5943797576 to your computer and use it in GitHub Desktop.
Save dacr/b56441215ce3b1b8a8499a5943797576 to your computer and use it in GitHub Desktop.
scalafx canvas example / published by https://github.com/dacr/code-examples-manager #148aaae2-1a56-44b4-b56a-9b1f1a018a80/2a63ed58fb5b4b2354ef2040364d622f36cb9d61
// summary : scalafx canvas example
// keywords : scala, user-interface, javafx, scalafx, canvas
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 148aaae2-1a56-44b4-b56a-9b1f1a018a80
// created-on : 2024-01-07T21:20:32+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
// To setup the right jdk with javafx enabled :
// nix-shell nix-shell-scalafx.nix (https://gist.github.com/dacr/f64acff9d7e128183f721038e7e0a94d)
// ---------------------
//> using scala "3.4.2"
//> using dep "org.scalafx::scalafx:21.0.0-R32"
// ---------------------
// coming from
// https://github.com/scalafx/scalafx/blob/master/scalafx-demos/src/main/scala/scalafx/canvas/CanvasDoodleTest.scala
import scalafx.Includes._
import scalafx.application.JFXApp3
import scalafx.application.JFXApp3.PrimaryStage
import scalafx.beans.property.DoubleProperty.sfxDoubleProperty2jfx
import scalafx.scene.canvas.Canvas
import scalafx.scene.input.MouseEvent
import scalafx.scene.paint.Stop.sfxStop2jfx
import scalafx.scene.paint.{Color, CycleMethod, LinearGradient, Stop}
import scalafx.scene.shape.Rectangle
import scalafx.scene.{Group, Scene}
/**
* Example adapted from code showed in [[http://docs.oracle.com/javafx/2/canvas/jfxpub-canvas.htm]].
*/
object CanvasDoodleTest extends JFXApp3 {
override def start(): Unit = {
val canvas = new Canvas(200, 200)
val rect = new Rectangle {
height = 400
width = 400
fill = new LinearGradient(0, 0, 1, 1, true, CycleMethod.Reflect, List(Stop(0, Color.Red), Stop(1, Color.Yellow)))
}
val rootPane = new Group
rootPane.children = List(rect, canvas)
stage = new PrimaryStage {
title = "Canvas Doodle Test"
scene = new Scene(400, 400) { root = rootPane }
}
canvas.translateX = 100
canvas.translateY = 100
val gc = canvas.graphicsContext2D
reset(Color.Blue)
canvas.onMouseDragged = (e: MouseEvent) => {
gc.clearRect(e.x - 2, e.y - 2, 5, 5)
}
canvas.onMouseClicked = (e: MouseEvent) => {
if (e.clickCount > 1) {
reset(Color.Blue)
}
}
def reset(color: Color): Unit = {
gc.fill = color
gc.fillRect(0, 0, canvas.width.get, canvas.height.get)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment