Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Ruby Programming
Previous Page Home Next Page

Canvas

Tk provides a Canvas widget with which you can draw and produce PostScript output. Here's a simple bit of code (adapted from the distribution) that will draw straight lines. Clicking and holding button 1 will start a line, which will be ``rubber-banded'' as you move the mouse around. When you release button 1, the line will be drawn in that position. Pressing button 2 on the mouse will dump out a PostScript representation of the drawing canvas, suitable for printing.

require 'tk'

class Draw   def do_press(x, y)     @start_x = x     @start_y = y     @current_line = TkcLine.new(@canvas, x, y, x, y)   end   def do_motion(x, y)     if @current_line       @current_line.coords @start_x, @start_y, x, y     end   end   def do_release(x, y)     if @current_line       @current_line.coords @start_x, @start_y, x, y       @current_line.fill 'black'       @current_line = nil     end   end   def initialize(parent)     @canvas = TkCanvas.new(parent)     @canvas.pack     @start_x = @start_y = 0     @canvas.bind("1", proc{|e| do_press(e.x, e.y)})     @canvas.bind("2", proc{ puts @canvas.postscript({}) })     @canvas.bind("B1-Motion", proc{|x, y| do_motion(x, y)}, "%x %y")     @canvas.bind("ButtonRelease-1",                  proc{|x, y| do_release (x, y)}, "%x %y")   end end

root = TkRoot.new{ title 'Canvas' } Draw.new(root) Tk.mainloop

A few mouse clicks, and you've got an instant masterpiece:

Missing screenshots/canvas.ps

``We couldn't find the artist, so we had to hang the picture....''
Ruby Programming
Previous Page Home Next Page

 
 
  Published under the terms of the Open Publication License Design by Interspire