2017-05-08 221 views
0

我想借鑑Canvas使用Scala.js在Scala.js上繪製畫布

在服務器端,我創建了一個簡單的頁面,用帆布:現在

import scalatags.Text.all._ 

html(
    body(
    div(
     h3("Let's draw something ️"), 
     canvas("canvas-id") 
    ) 
) 
) 

,在客戶端,我想用戶能夠繪製在畫布上的老鼠。

我該怎麼做?

回答

0

在客戶端,我通過ID獲取畫布,借鑑它,當用戶在將鼠標移動到:

get[Canvas]("canvas-id").fold(
    errorMsg => logger.warn("Could not find canvas. Error is {}", errorMsg), 
    canvas => drawOnCanvasWhenMouseMoved(canvas) 
) 

這是get方法,它返回一個類型的元素:

/** 
    * 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")) 
    } 
} 

其中ErrorMsg是一個簡單的值類:

case class ErrorMsg(value: String) extends AnyVal { 
    override def toString: String = value 
} 

我畫使用CanvasRenderingContext2D

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

/** 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")) 

結果:

drawing as gif