Skip to content

Instantly share code, notes, and snippets.

@stephen-soltesz
Last active August 9, 2017 03:03
Show Gist options
  • Save stephen-soltesz/9710452 to your computer and use it in GitHub Desktop.
Save stephen-soltesz/9710452 to your computer and use it in GitHub Desktop.
Three styles using gopherjs to draw an image on a canvas.
package main
import "github.com/gopherjs/gopherjs/js"
import "honnef.co/go/js/dom"
var imagePath = "resources/image.png"
func main() {
//draw_withGopherJS()
//draw_withDOM()
draw_withCustom()
}
func draw_withGopherJS() {
document := js.Global.Get("document")
canvas := document.Call("getElementById", "mycanvas")
context := canvas.Call("getContext", "2d")
img := js.Global.Get("Image").New()
img.Set("src", imagePath)
img.Call("addEventListener", "load", func() {
println("draw_withGopherJS")
context.Call("drawImage", img, 0, 0)
}, false)
}
func draw_withDOM() {
document := dom.GetWindow().Document()
canvas := document.GetElementByID("mycanvas")
context := canvas.Underlying().Call("getContext", "2d")
img := document.CreateElement("img").(*dom.HTMLImageElement)
//img.Src = imagePath // produces javascript: img.Src.src = imagePath
img.Set("src", imagePath)
img.AddEventListener("load", false, func(event dom.Event) {
println("draw_withDOM")
// context.Call("drawImage", img, 0, 0) // does not work.
context.Call("drawImage", img.Underlying(), 0, 0)
})
}
type Image struct {
js.Object
}
func newImage() *Image {
img := Image{js.Global.Get("Image").New()}
return &img
}
func (img *Image) AddEventListener(eventType string, callback func(), useCapture bool) {
img.Call("addEventListener", eventType, callback, useCapture)
}
func (img *Image) SetSrc(src string) {
img.Set("src", src)
}
func draw_withCustom() {
document := js.Global.Get("document")
canvas := document.Call("getElementById", "mycanvas")
context := canvas.Call("getContext", "2d")
img := newImage()
img.SetSrc(imagePath)
img.AddEventListener("load", func() {
println("draw_withCustom")
context.Call("drawImage", img.Object, 0, 0)
}, false)
}
/*
func draw_withDirect() {
document := dom.GetWindow().Document()
canvas := document.GetElementByID("mycanvas")
context := canvas.GetContext("2d")
img := document.CreateImageElement()
img.Src = imagePath
img.AddEventListener("load", func (event dom.Event) {
println("draw_withDirect")
context.DrawImage(img, 0, 0)
}, false)
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment