I have a problem while trying to draw onto a canvas GUI element.
I create a frame, a canvas and try to draw on the dc context of the canvas with the draw-line
method, but nothing happens. The frame with the canvas is shown, but the line isn't shown on the canvas.
(require racket/gui/base)
(define frame (new frame% [label "Frame"] [width 500] [height 500]))
(define canvas (new canvas% [parent frame]))
(define dc (send canvas get-dc))
(send dc draw-line 10 10 200 200)
(send frame show #t)
Does anybody know where I am wrong in the code above ?
Try this:
(require racket/gui/base)
(define frame (new frame% [label "Frame"] [width 500] [height 500]))
(define canvas (new canvas% [parent frame]))
(define dc (send canvas get-dc))
(send frame show #t)
(sleep/yield 1)
(send dc draw-line 10 10 200 200)
It seems that you need to show the frame first and then wait a bit to let the window get ready.
The problem is that even though you can draw on the canvas outside
a call to on-paint method of the canvas, the effect is temporary.
Any window activity that require the window to refresh (such as moving, and resizing) can potentially erase your drawing.
Therefore: Draw everything from within the paint-callback.
#lang racket
(require racket/gui/base)
(define frame (new frame% [label "Frame"] [width 500] [height 500]))
(define canvas (new canvas%
[parent frame]
[paint-callback
(λ(can dc) (send dc draw-line 10 10 200 200))]))
(define dc (send canvas get-dc))
(send frame show #t)
See Documentation on the canvas class for further information.