如何在Racket World中使用MouseEvent?求鼠标坐标显示示例
问题
我想要设计一个World程序,在鼠标当前位置显示其(x,y)坐标,鼠标移动时坐标数值和显示位置同步更新。我查阅了HtDW手册和DrRacket帮助文档中的MouseEvent相关内容,但未完全理解也未找到示例。现给出on-mouse-event的定义:
(on-mouse-event clack)
clack (-> World natural-number/c natural-number/c MouseEvent World)
Tells big-bang to call clack on the current world, the current x and y coordinates of the mouse, and a MouseEvent for every action of the mouse by the user of the computer. The result of the call becomes the current world.
请问on-mouse-event是否适用于该需求?若适用请提供示例,否则请告知在Racket中获取鼠标坐标的方法。
回答
on-mouse-event完全适用于你的需求。它能捕获所有鼠标动作(包括移动),并提供当前鼠标的x、y坐标,正好用来更新程序的世界状态,再配合渲染函数就能实现坐标的实时显示。
以下是完整的示例代码:
#lang racket/gui (require 2htdp/universe 2htdp/image) ; 定义世界状态:存储当前鼠标的x、y坐标 (struct mouse-pos (x y) #:transparent) ; 初始世界状态:鼠标在(0,0)位置 (define initial-world (mouse-pos 0 0)) ; 鼠标事件处理函数:仅响应移动事件,更新世界状态 (define (handle-mouse w x y event) (cond [(mouse=? event "move") (mouse-pos x y)] [else w])) ; 非移动事件保持原状态 ; 渲染函数:在当前鼠标位置显示坐标文本 (define (draw-world w) (place-image (text (format "(~a, ~a)" (mouse-pos-x w) (mouse-pos-y w)) 16 "black") (mouse-pos-x w) (mouse-pos-y w) (empty-scene 800 600 "white"))) ; 启动big-bang程序 (big-bang initial-world [on-mouse handle-mouse] [to-draw draw-world])
代码说明:
mouse-pos结构体用来存储当前鼠标的坐标,#:transparent方便查看状态handle-mouse函数只会在鼠标移动时更新世界的坐标,其他鼠标事件(点击、滚动等)不改变状态draw-world函数把坐标文本绘制在当前鼠标位置,背景是800x600的白色画布- 启动
big-bang时,通过[on-mouse handle-mouse]绑定鼠标事件处理逻辑,[to-draw draw-world]绑定渲染逻辑
运行这段代码后,移动鼠标就能看到坐标文本跟着鼠标移动,数值实时更新。
内容的提问来源于stack exchange,提问作者RadMan
相关产品推荐
相关产品推荐

