Updated 2018-06-05 06:54:54 by kpv

Keith Vetter 2018-06-04 -- The coordinate system for the canvas widget has its origin in the top left, indeed most graphical coordinates are set up that way. But sometimes it's more natural to have the origin in the middle of the widget.

Here's a little snippet that changes the coordinate system for a canvas so that 0,0 is located in the center of the widget. It works by binding to the <Configure> event and updating the canvas's scroll region. I first saw this trick on the SymDoodle page by Richard Suchenwirth.

Here's the code along with a simple demo:
package require Tk

pack [canvas .c -width 200 -height 200 -bd 0 -highlightthickness 0]
bind .c <Configure> {apply {{W h w} {
    set h [expr {$h / 2.0}]
    set w [expr {$w / 2.0}]
    $W config -scrollregion [list -$w -$h $w $h]
}} %W %h %w}


.c create line -100 -100 100 100 -fill cyan -width 20
.c create line 100 -100 -100 100 -fill cyan -width 20
.c create line -100 -100 100 100 -fill black -width 1
.c create line 100 -100 -100 100 -fill black -width 1
.c create rect -100 -100 100 100 -fill {} -outline red -width 50

.c create line 40 -10 0 0 -arrow last
.c create text 40 -10 -text "(0,0)" -anchor sw -tag x

return