使用Scala.js在画布上绘制
我想画一幅图画 在服务器端,我创建了一个带有画布的简单页面:使用Scala.js在画布上绘制,scala,html5-canvas,scala.js,Scala,Html5 Canvas,Scala.js,我想画一幅图画 在服务器端,我创建了一个带有画布的简单页面: import scalatags.Text.all._ html( body( div( h3("Let's draw something On the client side, I get the canvas by its ID and draw on it when the user moves the mouse over it: get[Canvas]("canvas-id").fold( e
import scalatags.Text.all._
html(
body(
div(
h3("Let's draw something On the client side, I get the canvas by its ID and draw on it when the user moves the mouse over it:
get[Canvas]("canvas-id").fold(
errorMsg => logger.warn("Could not find canvas. Error is {}", errorMsg),
canvas => drawOnCanvasWhenMouseMoved(canvas)
)
导入scalatags.Text.all_
html(
身体(
div(
h3(“让我们在客户端绘制一些的东西,我通过画布的ID获取画布,并在用户将鼠标移到画布上时在画布上绘制:
/**
* Gets an element of type `T` by an `elementId`. Returns either the element if
* found or an [[ErrorMsg]].
*/
def get[T: ClassTag](elementId: String): Either[ErrorMsg, T] = {
val queryResult = document.querySelector(s"#$elementId")
queryResult match {
case elem: T => Right(elem)
case other => Left(ErrorMsg(s"Element with ID $elementId is $other"))
}
}
这是返回类型化元素的get
方法:
case class ErrorMsg(value: String) extends AnyVal {
override def toString: String = value
}
其中ErrorMsg
是一个简单的值类:
private def drawOnCanvasWhenMouseMoved(canvas: Canvas) = {
getContext2D(canvas).fold(
errorMsg => logger.warn("Couldn't get rendering context of canvas: {}. Error: {}", canvas, errorMsg),
context => canvas.onmousemove = { e: MouseEvent => drawOnCanvas(e, context) }
)
def drawOnCanvas(e: MouseEvent, context: CanvasRenderingContext2D) = {
val x = e.clientX - canvas.offsetLeft
val y = e.clientY - canvas.offsetTop
context.fillStyle = "green"
context.fillRect(x, y, 2, 2)
}
}
我使用以下命令绘制:
最后,为了获得渲染上下文,我使用getContext
:
结果:
如果用鼠标画线需要两个位置,会发生什么情况?@MHJ:看一看CanvasRenderingContext2D
。
/** Returns either this [[Canvas]]' [[CanvasRenderingContext2D]] or
* an [[ErrorMsg]] if that fails. */
private def getContext2D(canvas: Canvas): Either[ErrorMsg, CanvasRenderingContext2D] =
if (canvas != null)
canvas.getContext("2d") match {
case context: CanvasRenderingContext2D => Right(context)
case other => Left(ErrorMsg(s"getContext(2d) returned $other"))
}
else
Left(ErrorMsg("Can't get rendering context of null canvas"))