06.01.2013 Views

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

342 <strong>Learning</strong> <strong>Processing</strong><br />

without pausing your <strong>Processing</strong> sketch, allowing the sketch <strong>to</strong> multitask and continue animating while<br />

the data retrieval is in process.<br />

Th e library functions in a similar manner <strong>to</strong> the <strong>Processing</strong> video library, which we became familiar with in<br />

Chapter 16. To retrieve a web page, you must create an instance of an HTMLRequest object, passing in a<br />

reference <strong>to</strong> the the sketch itself ( this ) and the URL you want <strong>to</strong> request.<br />

HTMLRequest req = new HTMLRequest(this, " http://www.yahoo.com " );<br />

Th e request will not begin, however, until you call makeRequest( ).<br />

req.makeRequest();<br />

Finally, <strong>to</strong> receive the data, you must write a function called netEvent( ) . Th is function will be invoked the<br />

instant the request is fi nished and data is available.<br />

Th is function is another example of a callback function, the same as captureEvent( ) (see Chapter 16) or<br />

mousePressed( ) . In this case, instead of an event being triggered when the user clicks the mouse or an<br />

image from the camera is available, the event is triggered when the HTML request fi nishes (or XML as<br />

we will see in a moment).<br />

Th e HTML source of the web page is returned as a String via the function readRawSource( ) .<br />

void netEvent(HTMLRequest ml) {<br />

String html = ml.readRawSource();<br />

println(html);<br />

}<br />

Example 18-7 retrieves Yahoo’s homepage every ten seconds using the simpleML library. Th e<br />

visualization here is arbitrary (lines are colored according <strong>to</strong> the characters in Yahoo’s HTML source);<br />

however, what is important is <strong>to</strong> notice how the animation never pauses while waiting for the data <strong>to</strong><br />

arrive .<br />

Example 18-7: Loading a URL with simpleML<br />

import simpleML.*;<br />

// A Request object, from the library<br />

HTMLRequest htmlRequest;<br />

Timer timer = new Timer(5000);<br />

String html = " " ; // String <strong>to</strong> hold data from request<br />

int counter = 0; // Counter <strong>to</strong> animate rectangle across window<br />

int back = 255; // Background brightness<br />

void setup() {<br />

size(200,200);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!