class RatatuiRuby::Widgets::Canvas
Provides a drawing surface for custom shapes.
Standard widgets cover standard cases. Sometimes you need to draw a map, a custom diagram, or a game. Character grids are too coarse for fine detail.
This widget increases the resolution. It uses Braille patterns or block characters to create a “sub-pixel” drawing surface.
Use it to implement free-form graphics, high-resolution plots, or geographic maps.
Examples
Canvas.new( x_bounds: [-180, 180], y_bounds: [-90, 90], shapes: [ Shape::Map.new(color: :green, resolution: :high), Shape::Circle.new(x: 0, y: 0, radius: 10, color: :red), Shape::Label.new(x: -122.4, y: 37.8, text: "San Francisco") ] )
Attributes
The background color of the canvas.
Optional wrapping block.
The marker type used for drawing.
:braille (high res), :half_block, :dot, :block, :bar.
Array of shapes to render.
Includes {Shape::Line}, {Shape::Circle}, {Shape::Map}, etc.
- min, max
-
range for the x-axis.
- min, max
-
range for the y-axis.
Public Class Methods
Source
# File lib/ratatui_ruby/widgets/canvas.rb, line 231 def initialize(shapes: [], x_bounds: [0.0, 100.0], y_bounds: [0.0, 100.0], marker: :braille, block: nil, background_color: nil) super( shapes:, x_bounds: [Float(x_bounds[0]), Float(x_bounds[1])], y_bounds: [Float(y_bounds[0]), Float(y_bounds[1])], marker:, block:, background_color: ) end
Creates a new Canvas.
- shapes
-
Array of Shapes.
x_bounds-
Array of [min, max] (Numeric, duck-typed via
to_f). y_bounds-
Array of [min, max] (Numeric, duck-typed via
to_f). - marker
-
Symbol (default:
:braille). - block
-
Block(optional). background_color-
Color (optional).
Public Instance Methods
Source
# File lib/ratatui_ruby/widgets/canvas.rb, line 272 def get_point(x, y) left, right = x_bounds bottom, top = y_bounds # Check bounds return nil if x < left || x > right || y < bottom || y > top width = right - left height = top - bottom # Avoid division by zero return nil if width <= 0.0 || height <= 0.0 # Normalize to [0.0, 1.0] range normalized_x = (x - left) / width normalized_y = (top - y) / height # Y inverted: top is 0, bottom is 1 [normalized_x, normalized_y] end
Converts canvas coordinates to normalized grid coordinates.
Hit testing and layout decisions need to know where a canvas point falls within the drawing surface. This method maps from the canvas coordinate system to normalized [0.0, 1.0] coordinates.
Use it to determine if a click or touch event lands within the canvas bounds, and where proportionally.
- x
-
X coordinate in canvas coordinate system.
- y
-
Y coordinate in canvas coordinate system.
Returns an Array [normalized_x, normalized_y] where each value is between 0.0 and 1.0, or nil if the point is outside the canvas bounds.
Example
canvas = Canvas.new(x_bounds: [0.0, 100.0], y_bounds: [0.0, 50.0]) canvas.get_point(50.0, 25.0) # => [0.5, 0.5] (center) canvas.get_point(0.0, 0.0) # => [0.0, 1.0] (bottom-left) canvas.get_point(101.0, 0.0) # => nil (out of bounds)