Version 0 of Getting the Canvas View Area in Pixels

Updated 2001-10-27 06:00:07

GPS Fri Oct 26, 2001: I had some trouble trying to figure out how to get the canvas view area in pixels for a game I'm writing called The Adventures of Baldo the Alien, so I devised the code below. Now it seems so obvious, but at the time it definitely wasn't. I guess I expected the canvas to have a builtin command that would tell me stuff like this, but I couldn't find a command to do it, so I wrote my own.

Enjoy!


  #!/usr/local/bin/wish8.3

  proc getCanvasViewArea {win} {

        foreach {junk junk totalXArea totalYArea} [$win cget -scrollregion] {}
        set xview [$win xview]
        set yview [$win yview]

        set xstart [expr {int([lindex $xview 0] * $totalXArea)}]
        set xend [expr {int([lindex $xview 1] * $totalXArea)}] 

        set ystart [expr {int([lindex $yview 0] * $totalYArea)}]
        set yend [expr {int([lindex $yview 1] * $totalYArea)}] 


        return [concat $xstart $xend $ystart $yend]
  }

  #Just some simple demonstration code
  proc main {} {
        pack [canvas .c -scrollregion {0 0 5000 500} -xscrollcommand ".s set"]
        pack [scrollbar .s -command ".c xview" -orient horizontal] -fill x

        pack [label .l -text [getCanvasViewArea .c]]
        pack [button .b -text "Get View Area" -command {
                .l config -text [getCanvasViewArea .c]
        }]
  }
  main