Drawing in an invisible canvas

Arjen Markus (22 november 2018) Today I realised that you do not need to put a canvas in a top level window (manage it) to still use it. Ordinarily I do something like:

pack [canvas .c]
... draw graphical objects

But you can simply do:

canvas .c
# Draw a line ...
.c create line 10 100 200 200 -fill blue -width 5

The canvas may not be visible, but it does contain the line, as you will see if you put it into a top level window or the like:

pack .c

Easy to try in a "wish" console.

At first sight, this does not to be very useful, but it also works with pdf4tcl:

# plotlinpr.tcl --
#     Simple plot of linear programming problem
#
package require pdf4tcl

#
# DO NOT pack the canvas, only create it ...
#
#pack [canvas .c -bg white -width 400 -height 300]
canvas .c -bg white -width 400 -height 300

.c create line  50 250 350 250 -width 4
.c create line  50 250  50  50 -width 4
.c create text 200 270 -text "X"
.c create text  30 150 -text "Y" -angle 90

.c create text 150  40 -text "Constraints" -fill blue
.c create line  50 100 350 200 -fill blue
.c create line 150  50 275 250 -fill blue

.c create text 180 170 -text "Optimum" -fill red
.c create line  90  50 332 250 -fill red -width 4

after 1000 {
    set pdf1 [::pdf4tcl::new %AUTO% -paper {12.0c 8.0c}]
    $pdf1 canvas .c -width 13.4c
    $pdf1 write -file linear_programming.pdf

    set go 1
}

So this trick allows you to produce pictures in the background.