参考源代码为here
当我访问http://localhost:12345/target/scala-2.11/classes/index-dev.html
Uncaught TypeError: $g.require is not a function$c_Lexample_ScalaJSExample$.main__Lorg_scalajs_dom_raw_HTMLCanvasElement__V @ ScalaJSExample.scala:22$c_Lexample_ScalaJSExample$.$$js$exported$meth$main__Lorg_scalajs_dom_raw_HTMLCanvasElement__O @ ScalaJSExample.scala:21$c_Lexample_ScalaJSExample$.main @ ScalaJSExample.scala:21(anonymous function) @ VM242:1(anonymous function) @ workbench.js:63
Funnel.scala
package example
import scala.scalajs.js
@js.native
trait Funnel extends js.Object {
def draw(values: js.Array[js.Array[Any]], options: js.Object): Unit = js.native
}
ScalaJSExample.scala:
package example
import scala.scalajs.js.Object
import scala.scalajs.js.annotation.JSExport
import org.scalajs.dom
import org.scalajs.dom.html
import scala.util.Random
import scala.scalajs.js
import js.Dynamic.{global => g}
import js.DynamicImplicits._
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)
}
@JSExport
object ScalaJSExample {
@JSExport
def main(canvas: html.Canvas): Unit = {
val ctx = canvas.getContext("2d")
.asInstanceOf[dom.CanvasRenderingContext2D]
val Funnel = js.Dynamic.global.require("d3-funnel")
val chart = js.Dynamic.newInstance(Funnel)("#funnel").asInstanceOf[Funnel]
val data = js.Array(js.Array("Plants", 5000))
val options = new Object()
chart.draw(data, options)
var count = 0
var p = Point(0, 0)
val corners = Seq(Point(255, 255), Point(0, 255), Point(128, 0))
def clear() = {
ctx.fillStyle = "black"
ctx.fillRect(0, 0, 255, 255)
}
def run = for (i <- 0 until 10){
if (count % 3000 == 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)
}
dom.setInterval(() => run, 50)
}
}