The app is finished, but it's far from having everything you'd expect from a drawing program. This page suggests ideas to take it further, from the most approachable to the most ambitious.
There are no ready-made solutions. For each idea, you'll find what we're trying to achieve, the concepts to look up (keywords to type into a search engine or the Rust documentation), the chapters of the tutorial to reread, and a few hints. The hints are hidden: click to show them, but try without them first.
All the ideas start from the final code, the one in the ch10-export tag. They're independent: pick the ones you like, in any order.
Freehand drawing#
Difficulty: medium
This is the feature our app misses the most: drawing freely with the mouse, like with Paint's pencil, leaving a trail that follows the cursor.
Concepts to look up: interpolating between two points, vector or raster software.
Chapters to reread: chapter 3 (lines and the thick line exercise), chapter 5 (pressing, dragging, releasing) and chapter 11 (vector or raster).
Hints
- The mouse only gives one position per frame. If you move it fast, two consecutive positions can be dozens of pixels apart. Coloring only those points gives a dotted trail: you need to connect each point to the previous one with a line.
- There's a choice to make, the one from chapter 11. Either the stroke is a new shape, for example
Shape::Stroke(Vec<Vec2>)with the list of points the mouse went through: it then stays selectable and movable like the other shapes. Or you add a second canvas that's never cleared, which you paint on directly, like the real Paint: the stroke is then nothing more than a set of pixels. - For a thicker stroke, reuse the idea from the thick line exercise in chapter 3: a small disc at each step.
Hollow shapes#
Difficulty: easy
Being able to draw a hollow rectangle or circle, with only its outline, on top of filled shapes. For example, a key that switches between the two modes.
Concepts to look up: a boolean in a struct.
Chapters to reread: chapter 3 (the circle outline exercise) and chapter 6 (adding a field to every shape).
Hints
- Each shape needs to know whether it's filled or hollow: a
filled: boolfield inRectandCircle, set at creation time from the current mode. - For the outline of a rectangle, four lines are enough. For the circle, the exercise in chapter 3 gives the method.
- Think about
contains: should you be able to select a hollow circle by clicking in the middle, or only on its edge? Both make sense.
Line thickness#
Difficulty: easy
Choosing the thickness of lines, for example with the + and - keys, instead of always having one pixel.
Concepts to look up: none new, it's all been covered.
Chapters to reread: chapter 3 (the thick line exercise) and chapter 7 (contains for lines).
Hints
- The current thickness is a field of
App, like the color. EachLinegets its own when it's created. - For selection, the distance accepted in
Line::containsshould grow with the thickness, otherwise a very thick line can only be selected by clicking right in its middle.
Saving as PNG#
Difficulty: easy
PPM is simple, but few programs open it. Also save as PNG, the most common image format.
Concepts to look up: the png crate, docs.rs.
Chapters to reread: chapter 4 (adding a dependency) and chapter 10 (exporting).
Hints
- Add the
pngcrate withcargo add, and read the writing example in its documentation on docs.rs. It needs the width, the height, and the pixels as RGB bytes one after the other: that's exactly what theVec<u8>of ourImageholds. - Writing can fail in several ways. Look at which error type the crate returns, and how to send it up with
?.
Drawing lines with Bresenham#
Difficulty: medium
Our draw_line computes each point with a multiplication and a division. Bresenham's algorithm draws the same line with only additions and comparisons. It's the classic algorithm for drawing lines, and you'll find it in many drawing libraries.
Concepts to look up: Bresenham's line algorithm, accumulated error.
Chapters to reread: chapter 3 (draw_line).
Hints
- The idea: for a mostly horizontal line, we move one pixel in
xat each step, and keep an "error" that says how far the real line is from the pixel we just colored. When it goes past half a pixel, we move up or down one step iny, and correct the error. - The best-known version handles all eight directions at once, with
dx,dyand the sign of the steps. You'll find it easily by searching for "Bresenham line algorithm". - To check, draw the same line with
draw_lineand with your version, one on top of the other: the pixels should be the same, or almost.
Undo and redo#
Difficulty: medium
Ctrl+Z to undo the last action, and Ctrl+Y to redo it, whether it's an addition, a move, a deletion or a color change.
Concepts to look up: undo history, Clone, stack.
Chapters to reread: chapter 5 (the exercise that removes the last rectangle) and chapter 7 (indexes that become wrong).
Hints
- The simplest method: before each change, keep a full copy of the list of shapes in a history, a
Vec<Vec<Shape>>. Undoing means putting the last copy back. Since our shapes deriveClone,self.shapes.clone()is enough to make the copy. - To be able to redo, you need a second list, which receives what you just undid. It gets emptied as soon as you make a new change.
- Watch out for
selectedafter an undo: the index can point to a shape that no longer exists. The simplest is to deselect everything. - For a move, you don't want a copy at every frame of the drag, just one, when the button is pressed.
The eraser#
Difficulty: medium
A tool that erases whatever the mouse touches.
Concepts to look up: vector or raster software.
Chapters to reread: chapter 7 (finding the shape under the mouse) and chapter 11.
Hints
- It all depends on the choice made for freehand drawing. In our vector app, the simplest eraser deletes every shape the mouse touches while dragging.
- If you added a canvas you paint on, the eraser can instead paint white on it, pixel by pixel, like the real Paint. It can then erase just part of a stroke.
The paint bucket#
Difficulty: medium
Clicking in an area to fill it with a color, up to the edges formed by other colors.
Concepts to look up: flood fill, breadth-first search, VecDeque.
Chapters to reread: chapter 3 (the canvas pixels) and chapter 11.
Hints
- The paint bucket works on pixels, not shapes. It needs a canvas that isn't redrawn at each frame, as for the raster version of freehand drawing.
- The idea: start from the clicked pixel, note its color, then color step by step all its neighbors that have the same color. A queue of pixels to process, a
VecDequeyou add neighbors to and take pixels from one by one, does the job very well. - You could write it with a function that calls itself for each neighbor, but on a large area, the program would crash: each call takes a bit of room on the stack, and there would be hundreds of thousands of nested calls.
Resizing a shape#
Difficulty: medium
When a shape is selected, show small squares at its corners. Dragging them changes its size.
Concepts to look up: resize handles.
Chapters to reread: chapter 7 (selection and Action::Moving) and chapter 8 (testing a click on a small rectangle).
Hints
- The handles are small
Rectvalues computed from the selected shape. Inon_press, you test them before the shapes, like the buttons. - A new variant, for example
Action::Resizing { index, corner }, lets you know which handle is being dragged. - For a circle, one handle is enough: its distance to the center gives the new radius. For a line, the two ends make very good handles.
Zooming and moving around the drawing#
Difficulty: medium
Enlarging the drawing to work on details, and dragging it to see another part.
Concepts to look up: screen coordinates and drawing coordinates, coordinate transformation.
Chapters to reread: chapter 5 (the mouse position) and chapter 7 (translate).
Hints
- There are now two coordinate systems: the drawing's, where the shapes live, and the screen's, in pixels. With a zoom
zand an offsetoffset, a point of the drawing shows up on screen at(point - offset) * z. - When drawing, you convert the shapes' coordinates to the screen. And the other way around, the mouse position must be converted to the drawing before being used to select or draw.
- The interface, on the other hand, must not zoom: the toolbar stays in place and at its size.
Saving and reopening a drawing#
Difficulty: medium
A PPM file keeps the image, but not the shapes: you can't reopen the drawing to keep moving the rectangles. Save the shapes themselves, and be able to load them back.
Concepts to look up: serialization, the serde crate, the JSON format, or a homemade text format. To go even further: the SVG format.
Chapters to reread: chapter 6 (enum Shape) and chapter 10 (writing a file).
Hints
- A homemade text format works very well: one shape per line, for example
rect 120 140 340 240 ff8800. To read the file back, split each line withsplit_whitespaceand convert each piece withparse, which returns aResult. - The
serdecrate can do all of this automatically: you add aderiveon your structs, and it takes care of writing and reading them. - SVG is a vector image format that browsers can read:
<rect>,<circle>and<line>map directly to our three shapes. Exporting to SVG gives an image that stays sharp at any zoom level.
Opening an image#
Difficulty: medium
Opening an existing PPM file and showing it as the background, to draw on top of it.
Concepts to look up: reading a file in Rust, BufReader, your own error enum.
Chapters to reread: chapter 2 (the PPM format) and chapter 3 (u32_to_rgb and its reverse).
Hints
- You need to do the reverse of
save_ppm: read the header (P6, the width, the height,255), then the pixel bytes, three per pixel. - Lots of things can go wrong: the file doesn't exist, it isn't a PPM, it's shorter than announced. An
enumwith one variant per possible error lets you describe them properly, and send them up with?. - To show it, the image is copied into the canvas at the start of each frame, in place of the
clear(WHITE).
Smooth lines#
Difficulty: hard
Our diagonal lines look like staircases. Smooth them out, by partially coloring the pixels that are only half on the line.
Concepts to look up: anti-aliasing, Xiaolin Wu's algorithm, color blending.
Chapters to reread: chapter 3 (draw_line and colors as u32).
Hints
- The idea: a pixel half covered by the line gets a mix of half the line's color and half the color already there.
- To blend two colors, split them into red, green and blue, blend each component separately, then put them back together.
u32_to_rgbandrgb_to_u32finally get used in both directions.
Layers and transparency#
Difficulty: hard
Semi-transparent shapes that let you see what's underneath, and several layers you can show or hide.
Concepts to look up: alpha channel, alpha compositing ("over").
Chapters to reread: chapter 3 (the color format) and chapter 8 (drawing order).
Hints
- The unused byte of our
0x00RRGGBBcolors can be used to store opacity, what's called the alpha channel. - Drawing a semi-transparent pixel is the same blend as for smooth lines, with the opacity as the proportion.
- A layer is simply a list of shapes. The final drawing is the stack of layers, from first to last.
Writing text#
Difficulty: hard
A text tool: you click, you type, and the text appears in the drawing.
Concepts to look up: font rasterization, the fontdue crate, text input with minifb.
Chapters to reread: chapter 4 (the keyboard) and chapter 6 (a new shape).
Hints
- A font describes curves, not pixels. The
fontduecrate turns each letter into a small grid that says, for each pixel, how much it's covered. You then draw it like smooth lines. - minifb can report the characters typed on the keyboard: look in its documentation for how to receive typed text, rather than testing keys one by one.
Writing the PNG yourself#
Difficulty: hard
The same as the PNG export above, but without any crate: writing the file byte by byte, as we did for PPM.
Concepts to look up: structure of a PNG file, chunks, CRC32, zlib, Adler-32, DEFLATE in "stored" mode.
Chapters to reread: chapter 2 (writing bytes to a file) and chapter 3 (bitwise operations).
Hints
- A PNG starts with an 8-byte signature, followed by blocks called chunks. You need at least three:
IHDR(size and format),IDAT(the pixels) andIEND(the end). - Each chunk ends with a CRC32 checksum, which you can compute yourself in a few lines.
- The pixels must be compressed in the zlib format. But this format allows "uncompressed" blocks: you can produce a valid PNG without writing a real compressor, you just need to wrap the bytes properly and add the Adler-32 checksum.
In the browser#
Difficulty: hard
Running the app in a web page, with nothing to install.
Concepts to look up: WebAssembly, the wasm32 target, wasm-bindgen.
Chapters to reread: chapter 4 (minifb and the render loop).
Hints
- Rust can compile to WebAssembly, a format browsers can run. minifb has a part built for this target: start by looking at its examples and its documentation.
- A browser doesn't like a page that blocks in an endless loop. The
whileloop inmainwill probably need to be rethought, so that the browser itself calls the update for each frame. - Exporting a file doesn't work the same way in a browser: there's no folder to write into, you have to offer a download.
What's next#
If you add one of these features, or another one of your own, share it: an issue or a discussion on the GitHub repository, or a post on social media. I'll be glad to see what the app has become in your hands.