|
| 1 | +# How to make a wordcram that pops up extra information |
| 2 | +# when you click on a word. |
| 3 | +# |
| 4 | +# Each frame, we want to draw the wordcram, and some info |
| 5 | +# about the word that's been clicked on (or hovered over). |
| 6 | +# Each frame, you need to clean up what the last frame drew. |
| 7 | +# |
| 8 | +# Since laying out a wordcram is expensive, and there's |
| 9 | +# (currently) no way to quickly re-render a wordcram, |
| 10 | +# we don't want to make the wordcram in draw(). |
| 11 | +# (Besides, each frame would probably come out different.) |
| 12 | +# Instead, render the wordcram in the setup() method, and |
| 13 | +# cache it as a PImage. Then, in draw(), render that image |
| 14 | +# first, which will overlay the last frame's image. |
| 15 | +require 'ruby_wordcram' |
| 16 | + |
| 17 | +attr_reader :wc, :cached_image, :last_clicked_word |
| 18 | + |
| 19 | +def settings |
| 20 | + size(700, 400) |
| 21 | +end |
| 22 | + |
| 23 | +def setup |
| 24 | + sketch_title 'Clickable Words' |
| 25 | + background(255) |
| 26 | + # Make the wordcram |
| 27 | + @wc = WordCram.new(self).from_web_page('http://wikipedia.org') |
| 28 | + wc.draw_all |
| 29 | + # Save the image of the wordcram |
| 30 | + @cached_image = get |
| 31 | + # Set up styles for when we draw stuff to the screen (later) |
| 32 | + text_font(create_font('sans', 150)) |
| 33 | + text_align(CENTER, CENTER) |
| 34 | + @last_clicked_word = nil |
| 35 | +end |
| 36 | + |
| 37 | +def draw |
| 38 | + # First, wipe out the last frame: re-draw the cached image |
| 39 | + image(cached_image, 0, 0) |
| 40 | + # If the user's last click was on a word, render it big and blue: |
| 41 | + unless last_clicked_word.nil? |
| 42 | + no_stroke |
| 43 | + fill 255, 190 |
| 44 | + rect 0, height / 2 - text_ascent / 2, width, text_ascent + text_descent |
| 45 | + fill(30, 144, 13, 150) |
| 46 | + text(last_clicked_word.word, width / 2, height / 2) |
| 47 | + end |
| 48 | +end |
| 49 | + |
| 50 | +def mouse_clicked |
| 51 | + @last_clicked_word = wc.get_word_at(mouse_x, mouse_y) |
| 52 | +end |
0 commit comments