v/examples/js_dom_draw/draw.js.v

83 lines
2.0 KiB
V
Raw Normal View History

/*
2021-10-27 22:18:09 +02:00
import jsdom
fn get_2dcontext(canvas jsdom.IElement) ?jsdom.CanvasRenderingContext2D {
2021-10-27 22:18:09 +02:00
if canvas is jsdom.HTMLCanvasElement {
c := canvas.get_context('2d')
match c {
jsdom.CanvasRenderingContext2D {
2021-10-27 22:18:09 +02:00
return c
}
else {
return error('cannot fetch 2d context')
}
}
} else {
return error('canvas is not an HTMLCanvasElement')
}
}
fn draw_line(context jsdom.CanvasRenderingContext2D, x1 int, y1 int, x2 int, y2 int) {
2021-10-27 22:18:09 +02:00
context.begin_path()
context.set_stroke_style('black')
context.set_line_width(1)
context.move_to(x1, y1)
context.line_to(x2, y2)
context.stroke()
context.close_path()
}
struct DrawState {
mut:
drawing bool
x int
y int
}
2021-10-27 22:18:09 +02:00
fn main() {
document := jsdom.document
elem := document.get_element_by_id('myButton') ?
elemc := document.get_element_by_id('myCanvas') or { panic('no canvas') }
canv := jsdom.get_html_canvas_element(elemc) or { panic('expected canvas') }
context := canv.get_context_2d()
mut state := DrawState{}
canv.add_event_listener('mousedown', fn [mut state] (_ jsdom.IEventTarget, event jsdom.IEvent) {
state.drawing = true
2021-10-27 22:18:09 +02:00
if event is jsdom.MouseEvent {
state.x = event.offset_x()
state.y = event.offset_y()
2021-10-27 22:18:09 +02:00
}
})
canv.add_event_listener('mousemove', fn [context, mut state] (_ jsdom.IEventTarget, event jsdom.IEvent) {
if state.drawing {
2021-10-27 22:18:09 +02:00
if event is jsdom.MouseEvent {
draw_line(context, state.x, state.y, event.offset_x(), event.offset_y())
state.x = event.offset_x()
state.y = event.offset_y()
2021-10-27 22:18:09 +02:00
}
}
})
jsdom.window.add_event_listener('mouseup', fn [context, mut state] (_ jsdom.IEventTarget, event jsdom.IEvent) {
if state.drawing {
2021-10-27 22:18:09 +02:00
if event is jsdom.MouseEvent {
draw_line(context, state.x, state.y, event.offset_x(), event.offset_y())
2021-10-27 22:18:09 +02:00
}
state.x = 0
state.y = 0
state.drawing = false
2021-10-27 22:18:09 +02:00
}
})
elem.add_event_listener('click', fn [context, canv] (_ jsdom.IEventTarget, _ jsdom.IEvent) {
context.clear_rect(0, 0, canv.width(), canv.height())
})
}
*/
fn main() {
panic('jsdom is being refactored; This example will be available soon')
}