ExplorerCanvas: Interactive Web Apps
by Dave Hoover
|
Pages: 1, 2, 3
cosley-server.rb
require 'webrick'
include WEBrick
server = HTTPServer.new( :Port => 8053 )
server.mount("/", HTTPServlet::FileHandler, ".")
$location = [50, 50]
def location_json
"({\"x\":#{$location[0]},\"y\"<WBR>:#{$location[1]}})"
end
server.mount_proc("/squirrel/location") do |request, response|
response['Content-Type'] = "text/plain"
response.body = location_json
end
server.mount_proc("/squirrel/update") do |request, response|
$location = [ request.query["x"].to_i, request.query["y"].to_i ]
response['Content-Type'] = "text/plain"
response.body = location_json
end
trap("INT") { server.shutdown }
server.start
The updated location is extracted from the "/squirrel/update" request parameters, stored in a global variable, and converted into JSON on the way back to the client.
InteractiveCanvas.html
<html>
<head>
<script type="text/javascript" src="excanvas.js"></script>
<script type="text/javascript" src="prototype-1.4.0.js"></script>
<script type="text/javascript">
window.onload = function() {
startPolling();
setupClick();
};
function startPolling() {
new PeriodicalExecuter(function() {
new Ajax.Request('/squirrel/location', { onComplete: draw });
}, 1);
}
function setupClick() {
if ( document.addEventListener ) {
document.addEventListener("click", onClick, false);
} else if ( document.attachEvent ) {
document.attachEvent("onclick", onClick);
} else {
alert("Your browser will not work for this example.");
}
}
function onClick(e) {
var position = getRelativePosition(e);
new Ajax.Request('/squirrel/update',
{ parameters: "x=" + position.x + "&y=" + position.y,
onComplete: draw });
}
function draw(request) {
var position = eval(request.responseText);
if (position == undefined) { return; }
var context = $("zoo").getContext("2d");
context.clearRect(0, 0, $("zoo").width, $("zoo").height);
context.beginPath();
context.arc(position.x, position.y, 10, 0, 2*Math.PI, false);
context.closePath();
context.fill();
}
function getRelativePosition(e) {
var t = $("zoo");
var x = e.clientX+(window.pageXOffset||0);
var y = e.clientY+(window.pageYOffset||0);
do
x-=t.offsetLeft+parseInt(t.style.borderLeftWidth||0),
y-=t.offsetTop+parseInt(t.style.borderTopWidth||0);
while (t=t.offsetParent);
return {x:x,y:y};
}
</script>
</head>
<body>
<canvas id="zoo" width="500" height="300" style="border: 1px solid black"></canvas>
</body>
</html>
I added an Ajax.Request to the onClick function which sends the updated coordinates to the server. Then I refactored the JSON processing into the draw function so I could pass the draw function to both of the Ajax.Requests' onComplete callbacks. And that's it! The zoologists can now monitor and update the location of their baby red squirrel. It would not be difficult to extend this example to insert the location updates into a database in order to chart the movements and tendencies of the squirrel over time.