O'Reilly Forums: Whiteboard Example - O'Reilly Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Whiteboard Example Help implmenting your code

#1 User is offline   emcsq 

  • New Member
  • Pip
  • Group: Members
  • Posts: 3
  • Joined: 18-December 08

Posted 18 December 2008 - 08:33 AM

Anthony, first I must applaud your effort in writting such a large work. Like anything, the larger (more complex) it gets the more risk there is for error or oversight. I need a little help with your example for the White board. I have entered the first section starting on page 703 and ending on 707. When I attempt activating the WEB page I get an error on loading. I have isolated the problem to the 1st function (marked in Red), but fail to see the fault. Even after emptying the first function and leaving the shell it still errors. I have found similar functions on the internet and see no obvious error. I am working off of a Linux Server and accessing the internet with Internet Explorer 7.

I am hoping this section could start a discussion on the complete section Whiteboard and Chat. I will even donate an example page with the work in progress as long as it is not abused.

Below is the code for the first section as taken from the book based on how I understood the instructions. I retained the remark statements for ease of reading. Since you did not say where to add Walter Zorn's code I added the link inside the Wrapper.

You can see the WEB page in action (or not in action) at

Example in Operation

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns-"http://www.w3.org/1999/xhtml" xml:lang-"en">
<html>
<head>

<title>Whiteboard Example</title>
</head>
<body>
<div id=bodyWrapper>
<!--All content goes here -->
/* Path has been modified to protect WEB site */
<script type="text/javascript" src="http://XXX/XXX/ws_jsgraphics.js"> </script>
<script language=JavaScript>
<!--
/**
* This variable, POINT_SIZE , is the size of the pen drawing on the canvas
*/
var POINT_SIZE = 1;
/**
* This variable, POINT_COLOR, is the color of the pen drawing on the canvas.
*/
var POINT_COLOR = '#f00';
/**
* this variable, whiteboard, will be the instatntiation of the jsGraphics class.
*/
var whiteBoard = null;
/* Do all this when the page is done loading... */
Event.observe(window, 'load', function() {
/* Create a new canvas to use for the whiteboard */
whiteBoard = new jsGraphics('whiteBoard');
/* Set the initial color of the pen */
whiteBoard.setColor(POINT_COLOR);
/* Set the initial size of the pen */
whiteBoard.setStroke(POINT_SIZE);
/* Set up events to trap mouse events that occur on the /whiteBoard/ */
Event.observe('whiteBoard', 'mousedown', StartDrawing);
Event.observe('whiteBoard', 'mouseup', StopDrawing);
});


/**
* this function, StartDrawing, is called whenever there is a /mousedown/
* event on the whiteboard, and astarts drawin on the canvas.
*
* @param {object} e The current trapped event.
*/
function StartDrawing(e){
/* did the event actually happen on the whiteboard? */
if(Event.element(e).id == 'whiteBoard')
DrawPoint(Event.pointerX(e), Event.pointerY(e));
Event.observe('whiteBoard', 'mousemove', ContinueDrawing);
}
/**
* This function, StopDrawing, is called whenever there is a /mouseup/
* event on the Whiteboard, and stops all drawing on the canvas.
*
* @param {object} e The current trapped event.
*/

function StopDrawing(e){
/* Stop observin /mousmove/ on the board and reest the last coordinates */
Event.stopObserving('whiteBoard', 'mousemove', ContinueDrawing);
lastPointx = -1;
lastPointY = -1;
}

/**
* This function, Continue Drawing is called as long as there is a
* /mouse/ event on the whiteboard, and draws on the canvas.
*
* @param {object} e The curretn trapped event.
*/
function ContinueDrawing(e){
/* did the event actually happen on the whiteboard? */
if(Event.element(e).id == 'whiteBoard')
DrawPoint(Event.pointerX(e), Event.pointerY(e));
}

/**
** This variable, X_OFFSET, is to act as the constant x-offset value of the
* whiteboard.
*/
var X_OFFSET = 10;
/**
** This variable, Y_OFFSET, is to act as the constant Y-offset value of the
* whiteboard.
*/
var Y_OFFSET = 10;
/**
** This variable, lastPointX, holds the last mouse event X-coordinate on the
* whiteboard.
*/
var lastPointX = -1;
/**
** This variable, lastPointY, holds the last mouse event Y-coordinate on the
* whiteboard.
*/
var lastPointY = -1;

/**
* This function, DrwaPoint, draws the lines on the wiiteboard as the mouse
* interaccts with it. It takes into consideration all offsets for canvas
* postion, and sets the last coordinates for the next line.
*
*@param {Integer} p_x The x-coordinate of the mouse event.
*@param {Integer} p_y The y-coordinate of the mouse event.
*/
function DrawPoint(p_x, p_y){
/* Take offsets into consideration */
p_x = p_x - (X_OFFSET + POINT_SIZE)
p_y = p_y - (Y_OFFSET + POINT_SIZE)
/* Is this the begining of a new drawin sequence? */
If(lastPointX == -1 || lastPointY == -1){
lastPointX = p_x;
lastPointy = p_y;
}

/* Draw the line */
whiteBoard.drawLine(p_x, p_y, lastPointX, lastPointY);
/* Display the line */
whiteBoard.paint();
/* Set the last coordinates to the curretn coordinates */
lastPointX = p_x;
lastPointY = p_y;
}
//-->
</script>
<div id='whiteBoard'></div
</div>
</body>
</html>

Looking forward to an interesting discussion on this intriguing topic.
0

#2 User is offline   anthony3 

  • Active Member
  • PipPip
  • Group: O'Reilly Author
  • Posts: 15
  • Joined: 17-September 08
  • Gender:Male
  • Location:Shiloh, IL

Posted 19 December 2008 - 09:18 AM

First, I'd like to say I'm glad to see my code being used. To your issues -- looking at the code you pasted, there are many issues with it. First, with a DOCTYPE of HTML 4.01, the xmlns and xml:lang are not needed in the html element. To keep these, switch your DOCTYPE to XHTML 1.0 or 1.1. Second, you have two opening html elements. Third, Walter Zorn's library is wz_jsgraphics.js, instead of ws_graphics.js (unless you renamed the file). The language=JavaScript attribute is depricated, and you should use type="text/javascript" instead. This code requires the Prototype library for using its event system (e.g. Event.observe(), Event.element(e).id). You could instead use the DOM Level 2 document.addEventListener and IE's event system's attachEvent, but this complicates things with cross-browser compatibility (which is why I am using Prototype in the first place -- easier cross-browser compatible coding).

So, for this code to work, you must add the Prototype library. Then, there are a couple of type errors in the StopDrawing and DrawPoint functions keeping this from working correctly. in StopDrawing, make sure the variable is lastPointX and not lastPointx. in DrawPoint, the if statement should be lowercase, and there are semicolons (for consistency) missing in the two statements above the if. Finally, lastPointY and not lastPointy.

Try these corrections and let me know if you have more luck.

Good luck!

Anthony
0

#3 User is offline   anthony3 

  • Active Member
  • PipPip
  • Group: O'Reilly Author
  • Posts: 15
  • Joined: 17-September 08
  • Gender:Male
  • Location:Shiloh, IL

Posted 19 December 2008 - 09:22 AM

Here is code I used to test:

HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Whiteboard Example</title>
<style type="text/css">
body { margin: 0; padding: 0; }
#whiteBoard { position: absolute; top: 10px; left:
10px; width: 800px; height: 400px; border: 1px solid #000; }
</style>
</head>
<body>
<div id="bodyWrapper">
<div id="whiteBoard"></div>
</div>
<!-- Path has been modified to protect WEB site -->
<script type="text/javascript" src="wz_jsgraphics.js"> </script>
<script type="text/javascript" src="prototype.js"> </script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var POINT_SIZE = 1;
var POINT_COLOR = '#f00';
var whiteBoard = null;

Event.observe(window, 'load', function() {
whiteBoard = new jsGraphics('whiteBoard');
whiteBoard.setColor(POINT_COLOR);
whiteBoard.setStroke(POINT_SIZE);

Event.observe('whiteBoard', 'mousedown', StartDrawing);
Event.observe('whiteBoard', 'mouseup', StopDrawing);
});

function StartDrawing(e){
if (Event.element(e).id == 'whiteBoard')
DrawPoint(Event.pointerX(e), Event.pointerY(e));
Event.observe('whiteBoard', 'mousemove', ContinueDrawing);
}

function StopDrawing(e){
Event.stopObserving('whiteBoard', 'mousemove', ContinueDrawing);
lastPointX = -1;
lastPointY = -1;
}

function ContinueDrawing(e){
if (Event.element(e).id == 'whiteBoard')
DrawPoint(Event.pointerX(e), Event.pointerY(e));
}

var X_OFFSET = 10;
var Y_OFFSET = 10;
var lastPointX = -1;
var lastPointY = -1;

function DrawPoint(p_x, p_y){
p_x = p_x - (X_OFFSET + POINT_SIZE);
p_y = p_y - (Y_OFFSET + POINT_SIZE);
if (lastPointX == -1 || lastPointY == -1) {
lastPointX = p_x;
lastPointY = p_y;
}
whiteBoard.drawLine(p_x, p_y, lastPointX, lastPointY);
whiteBoard.paint();
lastPointX = p_x;
lastPointY = p_y;
}
//--
><!]]>
</script>
</body>
</html>


I forgot to mention that your whiteBoard div will need to be positioned and sized with CSS. Hope this helps.
0

#4 User is offline   emcsq 

  • New Member
  • Pip
  • Group: Members
  • Posts: 3
  • Joined: 18-December 08

Posted 27 December 2008 - 07:51 AM

Anthony:

Thanks for the fast and detailed reply. I copied your example, loaded it and the prototype.js as you suggested. It worked better, but would not draw lines. I, as mentioned, am using Internet Explorier 7. I downloaded FireFox to run the test there. It works with FireFox 3.0 and works quite well.

Your code appears to work great, just not in IE 7.0. As is typical cross browser compatibility kills us more often than we like. I will need to explore the issue with IE 7.0.

Thanks again for the great support.

The code is currently running at Visit My Website

0

#5 User is offline   anthony3 

  • Active Member
  • PipPip
  • Group: O'Reilly Author
  • Posts: 15
  • Joined: 17-September 08
  • Gender:Male
  • Location:Shiloh, IL

Posted 28 December 2008 - 07:17 AM

There are two problems with the current code running in IE7. I added a CSS rule to #whiteBoard (background-color: #fff;) which makes it so you should then see what is being drawn on the canvas. For IE7, it is not, however, responding to the onmouseup event and stopping drawing. A cursory look did not reveal anything to me, and I will look into this "feature" more during the week.
0

#6 User is offline   anthony3 

  • Active Member
  • PipPip
  • Group: O'Reilly Author
  • Posts: 15
  • Joined: 17-September 08
  • Gender:Male
  • Location:Shiloh, IL

Posted 30 December 2008 - 08:25 AM

Okay, after doing more looking at this, the code itself is fine, except for saving processor time, the StartDrawing function should look like this:

CODE

function StartDrawing(e) {
if (Event.element(e).id == 'whiteBoard') {
DrawPoint(Event.pointerX(e), Event.pointerY(e));
Event.observe('whiteBoard', 'mousemove', ContinueDrawing);
}
}


The issue with the code in IE7 is the fact that IE's JScript parser is not very efficient, and can get bogged down, creating instances where the drawing may not be fluid. When the parser hangs, a straight line is drawn from the last "known" point to where the cursor is when the parser catches up, it loses the StopDrawing handler, and will continue to draw. Stop this action by double clicking on the canvas to get the event handlers back in sync.

I do not see a good way around this (as it is a limitation of IE7 -- maybe IE8 will be better). Perhaps losing the overhead of Prototype and writing all of the event handlers by hand will solve this? Shelley Powers' Learning JavaScript has an excellent chapter on Event handling for IE and the rest of the world.

Bottom line is browsers have limitations (for now), but strides are being made to make the JavaScript parsers quicker and more efficient all the time.

Hope this helps.
0

#7 User is offline   emcsq 

  • New Member
  • Pip
  • Group: Members
  • Posts: 3
  • Joined: 18-December 08

Posted 04 January 2009 - 06:45 AM

Anthony:

Thanks, I did a quick test with the new example and it still does not function at all in IE7, such is the world of browsers. I have Shella Powers book 'Learning JavaScript' and will take a look at what is needed in the way of Event Handling for IE7. On a slightly seperate topic; your program series on chat sessions. Do you have an example of the login.php code you intended in your call from chat.js on in 20.2? I can modify logout.php to imulate your intent, but wonder about your approach.

I did identify the database format needed for the chat programs for readers as follows:

database XXX (programmer's choice)

table messages
field msg_dte (key) (current timestamp)
field message (250)
field user_id (int)

table users
field user_id (key) (int)
field username (15)
field class (10)

Field widths are assumptions on my part.
0

#8 User is offline   anthony3 

  • Active Member
  • PipPip
  • Group: O'Reilly Author
  • Posts: 15
  • Joined: 17-September 08
  • Gender:Male
  • Location:Shiloh, IL

Posted 07 January 2009 - 09:19 AM

I am providing some code (as-is) as a starting point for logging in to chat. The basic flaw with my chat is it does not have any username creation associated with it, nor does it have any password protection -- I would add these to any real-life application, which should not be a big deal. Remember, I just whipped this code up, and I have not tested it.

CODE
<?php
/*
* The /users/ table should be something like this:
* user_id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMEMNT,
* username VARCHAR(20) NOT NULL UNIQUE KEY,
* class VARCHAR(10) NOT NULL,
* logged_in BIT NOT NULL DEFAULT 0,
* last_log DATETIME NULL
* The /excluded/ table should be something like this:
* exclude_id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
* bad_word VARCHAR(20) NOT NULL UNIQUE KEY
*/

session_start();

require_once('includes/db.php');

if (isset($_POST['username'])) {
if ($conn = @mysql_connect(SQL_SERVER, USERNAME, PASSWORD)) {
if (@mysql_select_db(DATABASE, $conn)) {
/* first check for vulgar words */
$sql = sprintf("SELECT bad_word FROM excluded WHERE bad_word = '%s';",
mysql_real_escape_string($_POST['username']));
if ($result = @mysql_query($sql)) {
if (@mysql_num_rows($result))
/* vulgarity found, so send this notice */
print('3');
else {
/* no vulgarity, next check to see if user is already logged in */
$sql = sprintf("SELECT username, logged_in, last_log FROM users WHERE",
mysql_real_escape_string($_POST['username']));
if ($result = @mysql_query($sql)) {
if ($row = @mysql_fetch_assoc($result)) {
/* should probably check to see if time is legit */
$last_log = strtotime($row['last_log']);
$now = time();
$diff = $now - $last_log;
if (!$row['logged_in'] ||
($row['logged_in'] && $diff > (3600 * 24))) {
/*
* log in the user if they are not logged in or they have
* been logged in for more than 1 day (3600 secs (1 hour) *
* 24 hours)
*/
$sql = sprintf("UPDATE users SET logged_in = 1, last_log = '%s' WHERE username = '%s'",
date('Y-m-j H:i:s'), mysql_real_escape_string($_POST['username']));
if (!@mysql_query($sql))
/* there was a problem logging in the user */
print('4');
else {
/* you may need this */
$_SESSION['username'] = $row['username'];
session_regenerate_id();
print('1');
}
} else
/* user is already logged in */
print('2');
} else
/* user does not exist, so would need to prompt to add or something other than 4 */
print('4');
} else {
/* problem with the SQL statement */
print('4');
}
@mysql_free_result($result);
} else
/* problem with the SQL statement */
print('4');
} else
/* problem switching to the database */
print('4');
@mysql_close($conn);
} else
/* problem connecting to the SQL server */
print('4');
} else
/* problem with the sent username */
print('4');
?>


Good luck!
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users