Skip to content

Instantly share code, notes, and snippets.

@tototoshi
Created June 28, 2014 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tototoshi/7528d12e177f5f62f0b9 to your computer and use it in GitHub Desktop.
Save tototoshi/7528d12e177f5f62f0b9 to your computer and use it in GitHub Desktop.
Scala.js で xhr で画像をとってきて表示する
package com.github.tototoshi.gifplayer
import scala.scalajs.js
import js.annotation.JSExport
import org.scalajs.dom
@JSExport
object GIFPlayer extends js.JSApp {
def main(): Unit = {
val xhr = new dom.XMLHttpRequest
xhr.open("GET", "/test.gif", true)
xhr.responseType = "arraybuffer"
xhr.onload = (e: dom.Event) => {
/* xhr.response は xhr.responseType で型が変わるので js.Any */
val arr = new dom.Uint8Array(xhr.response.asInstanceOf[dom.ArrayBuffer])
val byteArray = for (i <- 1 to arr.byteLength.toInt) yield arr(i - 1).toChar
val contentType = xhr.getResponseHeader("Content-type")
val src = "data:" + contentType + ";base64," + dom.btoa(byteArray.mkString)
val gifImage = dom.document.getElementById("gif")
gifImage.setAttribute("src", src)
}
xhr.send()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment