2017-05-08 17 views
0

CanvasScala.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方法であって、

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

ErrorMsgは単純な値のクラスである

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

私はgetContextを使用し、

最後
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) 
    } 
} 

、レンダリングコンテキストを取得するために:私は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")) 

結果:

drawing as gif

関連する問題