Canvas interaction

In this lesson, we will build a rectangle in a canvas, and make it moveable by mouse.

By the way, we learn, how to use event-fields.

To load the Tk extensions, enter

(require-extension tk)
(start-tk)

First, we create and pack the canvas c1:

(define c1 (tk 'create-widget 'canvas))
(tk/pack c1 #:expand #t #:fill 'both)

Then, we create a rectangular item r1 of white color and red outline:

(define r1 (c1 'create 'rectangle 10 10 60 60))
(c1 'itemconfigure r1 #:fill 'white #:outline 'red)

We see the result:

canvas_with_rectangle

We need variables to store the actual x and y position of the pointer and a procedure to initialise them:

(define pointer-x 0)
(define pointer-y 0)
(define (pointer-set! x y)
  (set! pointer-x x)
  (set! pointer-y y))

On mouse-click on rectangle r1, the procedure pointer-set! should be invoked with the event-fields %x and %y:

(c1 'bind r1 '<Button> `(,pointer-set! %x %y))

We need a procedure to move rectange r1:

(define (move-item canvas tag-or-id x y)
  (canvas 'move tag-or-id
	  (- x pointer-x)
	  (- y pointer-y))
  (pointer-set! x y))

function on mouse-drag on rectangle r1:

(c1 'bind r1 '<Button1-Motion>
    `(,(lambda (x y)
	 (move-item c1 r1 x y))
      %x %y))

Now, we can drag the rectangle across the canvas. Have fun!


© Author | Home | Sitemap