Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

JAVA SCRIPT - Using let in Your Browser Application

Using let in Your Browser Application


Problem

You’re interested in using let in your browser application, but aren’t sure which brows‐ ers support it (or other ECMAScript functionality), or what you need to do to get it to work.

Solution

Support for ECMAScript 6 functionality, such as let, can be difficult to determine, and may require setting flags, specifying JavaScript version numbers, or using specialized polyfills or other tools. Unfortunately, not all approaches are compatible across all the modern browsers. The support for let is a perfect example of fractured ES 6 support across browsers.

To use let in Firefox, you have to give a version number with the script tag:

<script type="application/javascript;version=1.7">
 if (true) {
 let i = 'testing let';
 console.log(i);
 }
 if (typeof i != 'undefined'){
 console.log(i);
 } else {
 console.log('undefined');
 }
</script>


In Firefox, the console output is what we would expect:


testing let
undefined

To get the same result in Internet Explorer 11, your HTML document must be HTML5, which means using the following DOCTYPE:

<!DOCTYPE html>

This puts IE 11 into edge mode, where many ES 6 features are supported. Unfortunately, IE 11 ignores any script block with a type of application/javascript;version=1.7, so you’ll have to remove the type setting for the script to work.

The same applies to Chrome. Chrome supports let if you remove Firefox’s peculiar use of type and if you enable the chrome://flags/#enable-javascript-harmony flag. In addition, you must also use strict mode, so the code needs to be modified to:


<script>
 'use strict';
 if (true) {
 let i = 'testing let';
 alert(i);
 }
 if (typeof i != 'undefined'){
 alert(i);
 } else {
 alert('undefined');
 }
</script>


This code snippet also works for IE, but not Firefox. The code also works in Opera if you enable the same Chrome Harmony flag (copy and paste the above flag URI into the location bar for Opera and click “Enable”). Safari doesn’t, at this time, support let.

EXPLAIN

The let keyword allows JavaScript developers to define block-level variables, rather than global variables or variables in a function block. 

An example is given in the solution, where the variable i is only available within the conditional block, but is undefined outside the block. JavaScript developers have pushed for the concept of let longer than most additions to ECMAScript 6, but its use in production applications must be restricted because of the difficulty to support it, as was demonstrated in the solution.

Yes, you can support it across browsers, but only when flags are set, and even then, Firefox doesn’t currently support a syntax that works for Chrome, IE, and Opera, and Safari is missing, altogether

The same holds for many of the ES 6 new language constructs: if the construct requires setting a browser flag, you have to assume your end user hasn’t set it so you can’t depend on it. This differs from supporting the new ES objects (covered in the rest of this chapter) because it’s easier to emulate a new object using a polyfill, than it is to emulate a new language construct. 

Even a translator-compiler (transpiler), such as Google’s Traceur, can only convert let into var, because there is no current workaround for the concept of let. Running the solution code snippet in the Traceur REPL (read-evaluate-print) results in the following: . 


$traceurRuntime.ModuleStore.getAnonymousModule(function() {
 "use strict";
 'use strict';
 if (true) {
 var i = 'testing let';
 alert(i);
 }
 if (typeof i != 'undefined') {
 alert(i);
 } else {
 alert('undefined');
 }
 return {};
});
//# sourceURL=traceured.js

In this case, the workaround is worse than not having a workaround, because var does not result in the same behavior as the use of let. The resulting print-out for the Traceur version is:


testing let
testing let


The variable i is printed out twice, as it is defined in the code outside the conditional block—the variable is no longer scoped to the block

JAVA SCRIPT - Adding Filter Effects to Video via Canvas

 Adding Filter Effects to Video via Canvas


Problem

You’re interested in not only playing video in your web page but also playing modified versions of the video, such as one that has been grayscaled, or manipulated in some way. 

Solution

Use HTML5 video with the Canvas element, playing the video to a scratch Canvas element:

function drawVideo() {
 var videoObj = document.getElementById("videoobj");
 // if not playing, quit
 if (videoObj.paused || videoObj.ended) return false;
 // draw video on canvas
 var canvasObj = document.getElementById("canvasobj");
 var ctx = canvasObj.getContext("2d");
 ctx.drawImage(videoObj,0,0,480,270);
 ...
 setTimeout(drawVideo,20);
}


You can then add the ability to capture the image data using the Canvas element’s getImageData(), modify the image data with whatever filter you want, and then play the image data to a second, visible Canvas element:


var pData = ctx.getImageData(0,0,480,270);
// grayscale it and set to display canvas
pData = grayScale(pData);
ctx2.putImageData(pData,0,0);


EXPLAIN

The best thing about all the new HTML5 media elements is how you can use them together. Using video and Canvas, you can not only provide custom controls, you can also provide custom video filters, too.

To play a video in a Canvas element, we’ll need to add both elements to the web page:


<video id="videoobj" controls width="480" height="270">
 <source src="videofile.mp4" type="video/mp4" />
 <source src="videofile.webm" type="video/webm" />
 </video>
 <canvas id="canvasobj" width="480" height="270"></canvas>

Both the canvas and video elements are the same width and height. To draw the video onto the canvas, we’re going to use the Canvas drawImage(). There are several variations of parameters we could use with this method, but the signature we’re interested in is the following:


void drawImage(
 in nsIDOMElement image,
 in float dx,
 in float dy,
 in float dw,
 in float dh
);

These parameters are:

• image: A reference to a Canvas element, an img element, or a Video element

• dx: x coordinate of the top-left corner of the source image

• dy: y coordinate of the top-left corner of the source image

• dw: Width of the source image (can be scaled)

• dh: Height of the source image (can be scaled)

Demonstrates a first pass at an application to modify the video playing the Canvas element. It just takes what’s showing in the video and plays it, as is, in the Canvas.

The application uses setTimeout() to test whether the video is still playing and grabs the video every 20 milliseconds, which is fast enough to provide smooth playback for human perceptions.

There is a timeupdate event handler for the Video element, but it’s only invoked every 200 milliseconds (per the W3C specification on the media elements), which is way too slow for our purposes.

A first cut at drawing video data to a canvas element


<!DOCTYPE html>
<head>
<title>Play video in canvas</title>
 <meta charset="utf-8" />
 <script>
 window.onload=function() {
 document.getElementById("videoobj").
 addEventListener("timeupdate", drawVideo, false);
 }
 function drawVideo() {
 var videoObj = document.getElementById("videoobj");
 var canvasObj = document.getElementById("canvasobj");
 var ctx = canvasObj.getContext("2d");
 ctx.drawImage(videoObj,0,0);
 }
 </script>
</head>
<body>
 <video id="videoobj" controls width="480" height="270">
 <source src="videofile.mp4" type="video/mp4" />
 <source src="videofile.webm" type="video/webm" />
 </video>
 <canvas id="canvasobj" width="480" height="270"></canvas>
</body>

In the code, during each time out event, the video is tested to see if it’s still playing before it’s grabbed and displayed in the Canvas element. The application works in all modern browsers.

The next step is to modify the video data before it’s streamed to the Canvas element. For the example, I’m going to do a crude modification of the original video to simulate how a person could perceive the video if they suffered from a form of color blindness known as protanopia.

This type of color blindness is one of the most common, and those who have it can’t perceive red light. I say “crude” because a much more accurate representation is so computationally expensive that the playback visibly stutters.

To modify the video playback, we need two things: the function to modify the data, and a scratch canvas object used to capture the video data, as it is, and then serve as our intermediate in the transformation.

We need a scratch Canvas element because we’re using the Canvas element’s getImageData() to access the actual video data, and putI mageData() to play the video data after it has been manipulated.

The getImageData() function returns an object consisting of three values: the width, the height, and the image data as a Uint8ClampedArray typed array.

Video with applied color blind filter, playing side by side with original 


<!DOCTYPE html>
<head>
<title>Protanopia</title>
 <meta charset="utf-8" />
 <script>
 // Protanopia filter
 function protanopia(pixels) {
 var d = pixels.data;
 for (var i=0; i<d.length; i+=4) {
 var r = d[i];
 var g = d[i+1];
 var b = d[i+2];
 //convert to an approximate protanopia value
 d[i] = 0.567*r + 0.433*g;
 d[i+1] = 0.558*r + 0.442*g;
 d[i+2] = 0.242*g + .758*b;
 }
 return pixels;
 }
 // event listeners
 window.onload=function() {
 document.getElementById("videoobj").
 addEventListener("play", drawVideo, false);
 }
 // draw the video
 function drawVideo() {
 var videoObj = document.getElementById("videoobj");
// if not playing, quit
 if (videoObj.paused || videoObj.ended) return false;
 // create scratch canvas
 var canvasObj = document.getElementById("canvasobj");
 var bc = document.createElement("canvas");
 bc.width=480;
 bc.height=270;
 // get contexts for scratch and display canvases
 var ctx = canvasObj.getContext("2d");
 var ctx2 = bc.getContext("2d");
 // draw video on scratch and get its data
 ctx2.drawImage(videoObj, 0, 0, 480, 270);
 var pData = ctx2.getImageData(0,0,480,270);
 // grayscale it and set to display canvas
 pData = protanopia(pData);
 ctx.putImageData(pData,0,0);
 setTimeout(drawVideo,20);
 }
 </script>
</head>
<body>
 <video id="videoobj" controls width="480" height="270">
 <source src="videofile.mp4" type="video/mp4" />
 <source src="videofile.webm" type="video/webm" />
 </video>
 <canvas id="canvasobj" width="480" height="270"></canvas>
</body>

JAVA SCRIPT - Controlling Video from JavaScript with the video Element

Controlling Video from JavaScript with the video Element


Problem

You want to embed video in your web page, without using Flash. You also want a con‐ sistent look for the video control, regardless of browser and operating system.


Solution

Use the HTML5 video element: 

<video id="meadow" poster="purples.jpg" >
 <source src="meadow.m4v" type="video/mp4"/>
 <source src="meadow.ogv" type="video/ogg" />
</video>


You can provide controls for it via JavaScript, as shown in Example 9-5. Buttons are used to provide the video control, and text in a div element is used to provide feedback on time during the playback.

Providing a custom control for the HTML5 video element :


<!DOCTYPE html>
<head>
<title>Meadow Video</title>
<script>
<style>
 video {
 border: 1px solid black;
 }
</style>
window.onload=function() {
 // events for buttons
 document.getElementById("start").addEventListener("click",startPlayback);
 document.getElementById("stop").addEventListener("click",stopPlayback);
 document.getElementById("pause").addEventListener("click",pausePlayback);
 // setup for video playback
 var meadow = document.getElementById("meadow");
 meadow.addEventListener("timeupdate",reportProgress);
 // video fallback
 var detect = document.createElement("video");
 if (!detect.canPlayType) {
 document.getElementById("controls").style.display="none";
 }
}
// start video, enable stop and pause
// disable play
function startPlayback() {
 var meadow = document.getElementById("meadow");
 meadow.play();
 document.getElementById("pause").disabled=false;
 document.getElementById("stop").disabled=false;
 this.disabled=true;
}
// pause video, enable start, disable stop
// disable pause
function pausePlayback() {
 document.getElementById("meadow").pause();
 this.disabled=true;
 document.getElementById("start").disabled=false;
 document.getElementById("stop").disabled=true;
}
// stop video, return to zero time
// enable play, disable pause and stop
function stopPlayback() {
 var meadow = document.getElementById("meadow");
meadow.pause();
 meadow.currentTime=0;
 document.getElementById("start").disabled=false;
 document.getElementById("pause").disabled=true;
 this.disabled=true;
}
// for every time divisible by 5, output feedback
function reportProgress() {
 var time = Math.round(this.currentTime);
 var div = document.getElementById("feedback");
 div.innerHTML = time + " seconds";
}
</script>
</head>
<body>
<video id="meadow" poster="purples.jpg" >
 <source src="meadow.m4v" type="video/mp4"/>
 <source src="meadow.ogv" type="video/ogg" />
</video>
<div id="feedback"></div>
<div id="controls">
<button id="start">Play</button>
<button id="stop">Stop</button>
<button id="pause">Pause</button>
</controls>
</body>


EXPLAIN

The new HTML5 video element, as with the HTML5 audio element, can be controlled with its own built-in controls, or you can provide your own. The media elements support the following methods: 

• play: Starts playing the video 

• pause: Pauses the video 

• load: Preloads the video without starting play 

• canPlayType: Tests if the user agent supports the video type The media elements don’t support a stop method, so the code emulates one by pausing video play and then setting the video’s currentTime attribute to 0, 

which basically resets the play start time. I also used currentTime to print out the video time, using Math.round to round the time to the nearest second.

The video control is providing two different video codecs: H.264 (.mp4), and Ogg Theora (.ogv). Firefox, Opera, and Chrome support Ogg Theora, but Safari and IE only support the H.264-formatted video. 

However, by providing both types, the video works in all of the browsers that support the video element. The video and audio controls are inherently keyboard-accessible. 

If you do replace the controls, you’ll want to provide accessibility information with your replacements. The video control doesn’t have built-in captioning, but work is underway to provide the API for captioning.


JAVA SCRIPT - Running a Routine When an Audio File Begins Playing

Running a Routine When an Audio File Begins Playing 


Problem

You want to provide an audio file and then pop up a question or other information when the audio file begins or ends playing.


Solution

Use the HTML5 audio element: 


<audio id="meadow" controls>
 <source src="meadow.mp3" type="audio/mpeg3"/>
 <source src="meadow.ogg" type="audio/ogg" />
 <source src="meadow.wav" type="audio/wav" />
 <p><a href="meadow.wav">Meadow sounds</a></p>
</audio>

and capture either its play event (playback has begun) or ended event (playback has finished):

var meadow = document.getElementById("meadow");
meadow.addEventListener("ended", aboutAudio);



then display the information:


function aboutAudio() {
 var info = 'This audio file is a recording from Shaw Nature Reserve';
 var txt = document.createTextNode(info);
 var div = document.createElement("div");
 div.appendChild(txt);
 document.body.appendChild(div);
}


EXPLAIN

HTML5 added two media elements: audio and video. These simple-to-use controls provide a way to play audio and video files without having to use Flash. In the solution, the audio element’s controls Boolean attribute is set, so the controls are displayed. 

The element has three source children elements, providing support for three different types of audio files: WAV, MP3, and Ogg Vorbis. 

The use of the source element allows different browsers to find the format (codec) that they support. For the example, the browser support is: 

• Firefox accepts either the WAV or Ogg Vorbis. It also accepts MP3, but uses the underlying operating system support to do so, rather than providing its own. 

• Opera supports WAV and Ogg Vorbis, but not MP3. 

• Chrome supports WAV, MP3, and Ogg Vorbis. 

• Safari supports MP3 and WAV. 

• IE supports the MP3.

A link to the WAV file is provided as a fallback, which means people using browsers that don’t support audio can still access the sound file. I could have also provided an object element, or other fallback content.

The media elements come with a set of methods to control the playback, as well as events that can be triggered when the event occurs. In the solution, the ended event is captured and assigned the event handler aboutAudio(), which displays a message about the file after the playback is finished. 

Notice that though the code is using a DOM Level 0 event handler with the window load event, it’s using DOM Level 2 event handling with the audio element. Browser support is erratic with this event handler, so I strongly recom‐ mend you use addEventListener(). However, onended does seem to work without problems when used directly in the element:


<audio id="meadow" src="meadow.wav" controls onended="alert('All done')">
 <p><a href="meadow.wav">Meadow sounds</a></p>
</audio>

It’s interesting to see the appearance of the elements in all of the browsers that currently support them. There is no standard look, so each browser provides its own interpreta‐ tion.

You can control the appearance by providing your own playback controls and using your own elements/CSS/SVG/Canvas to supply the decoration.

JAVA SCRIPT - Integrating SVG and the Canvas Element in HTML

 Integrating SVG and the Canvas Element in HTML


Problem

You want to use the canvas element and SVG together within a web page. 

Solution

One option is to embed both the SVG and the canvas element directly into the HTML page, and then access the canvas element from script within SVG:

<!DOCTYPE html>
<head>
<title>Canvas and SVG</title>
<meta charset="utf-8" />
</head>
<body>
<canvas id="myCanvas" width="400px" height="100px">
 <p>canvas item alternative content</p>
</canvas>
<svg id="svgelem" height="400">
 <title>SVG Circle</title>
 <script type="text/javascript">
 window.onload = function () {
 var context =
document.getElementById("myCanvas").getContext('2d');
 context.fillStyle = 'rgba(0,200,0,0.7)';
 context.fillRect(0,0,100,100);
 };
 </script>
 <circle id="redcircle" cx="100" cy="100" r="100" fill="red" stroke="#000" />
 </svg>
</body>

Or you can embed the canvas element as a foreign object directly in the SVG:

<!DOCTYPE html>
<html>
<head>
<title>Accessing Inline SVG</title>
<meta charset="utf-8">
</head>
<body>
<svg id="svgelem" height="400" width="600">
 <script type="text/javascript">
 window.onload = function () {
 var context2 = document.getElementById("thisCanvas").getContext('2d');
 context2.fillStyle = "#ff0000";
 context2.fillRect(0,0,200,200);
 };
 </script>
 <foreignObject width="300" height="150">
 <canvas width="300" height="150" id="thisCanvas">
 alternate content for browsers that do not support Canvas
 </canvas>
 </foreignObject>
 <circle id="redcircle" cx="300" cy="100" r="100" fill="red" stroke="#000" />
 </svg>
</body>
</html>


EXPLAIN 


 When the SVG element is embedded into the current web page, you can access HTML elements from within the SVG. However, you can also embed elements directly in SVG, using the SVG foreignObject element. This element allows us to embed XHTML, MathML, RDF, or any other XML-based syntax.

In both solutions, I was able to use getElementById(). However, if I want to manipulate the elements using other methods, such as getElementsByTagName(),

I have to be care‐ ful about which version of the method I use. For instance, I can use getElementsByTag Name() for the outer canvas element, but I would need to use the namespace version of the method, getElementsByTagNameNS, if the contained object is XML,

 such as RDF/ XML. Because the embedded object in the solution is HTML5, a namespace wasn’t necessary. Once you have the canvas context, use the element like you would from script within HTML: add rectangles, draw paths, create arcs, and so on.

Canvas? Or SVG?

Why would you use Canvas over SVG, or SVG over Canvas? The canvas element is faster in frame-type animations. With each animation, the browser only needs to redraw the changed pixels, not re-create the entire scene. 

However, the advantage you get with the canvas element animation lessen when you have to support a variety of screen sizes, from smartphone to large monitor. SVG scales beautifully.

Another advantage to SVG is that it figures in rich data visualizations with the assistance of powerful libraries, . But then, Canvas is used with 3D systems, such as WebGL, . 

But why choose one over the other? One use of SVG and Canvas together is to provide a fallback for the canvas element: the SVG writes to the DOM and persists even if Java‐ Script is turned off, while the canvas element does not. 

JAVA SCRIPT - Accessing SVG from Web Page Script

Accessing SVG from Web Page Script


Problem

You want to modify the contents of an SVG element from script within the web page. 


Solution

If the SVG is embedded directly in the web page, access the element and its attributes using the same functionality you would use with any other web page element:

var square = document.getElementById("ssquare");
square.setAttribute("width", "500");

However, if the SVG is in an external SVG file embedded into the page via an object element, you have to get the document for the external SVG file in order to access the SVG elements. The technique requires object detection because the process differs by browser:


// set element onclick event handler
window.onload=function () {
 var object = document.getElementById("object");
 var svgdoc;
 try {
 svgdoc = object.contentDocument;
 } catch(e) {
 try {
 svgdoc = object.getSVGDocument();
 } catch (e) {
 alert("SVG in object not supported in your environment");
 }
 }
 if (!svgdoc) return;
 var square = svgdoc.getElementById('square');
 square.setAttribute("width", "500");


EXPLAIN


 The first option listed in the solution accesses SVG embedded in an HTML file. You can access SVG elements using the same methods you’ve used to access HTML elements. The second option is a little more involved, and depends on retrieving the document object for the SVG document.

The first approach tries to access the contentDocument property on the object. If this fails, the application then tries to access the SVG document using getSVGDocument(). Once you have access to the SVG document object, you can use the same DOM methods you would use with elements native to the web page. Accessing SVG in an object element from script.


<!DOCTYPE html>
<head>
<title>SVG in Object</title>
<meta charset="utf-8" />
</head>
<body>
<object id="object" data="rect.svg"
style="padding: 20px; width: 600px; height: 600px">
<p>No SVG support</p>
</object>
<script type="text/javascript">
 var object = document.getElementById("object");
 object.onload=function() {
 var svgdoc;
 // get access to the SVG document object
 try {
 svgdoc = object.contentDocument;
 } catch(e) {
 try {
 svgdoc = object.getSVGDocument();
 } catch (e) {
 alert("SVG in object not supported in your environment");
 }
 }
 if (!svgdoc) return;
 var r = svgdoc.rootElement;
 // get SVG element and modify
 var square = svgdoc.getElementById('square');
 square.onclick = function() {
 var width = parseFloat(square.getAttribute("width"));
 width-=50;
 square.setAttribute("width",width);
 var color = square.getAttribute("fill");
 if (color == "blue") {
 square.setAttribute("fill","yellow");
square.setAttribute("stroke","green");
 } else {
 square.setAttribute("fill","blue");
 square.setAttribute("stroke","red");
 }
 }
 }
</script>
</body>


In addition to the different approaches to get the SVG document, you also have to handle browser differences in how the onload event handler works. Firefox and Opera fire the onload event handler for the window after all the document contents have loaded, in‐ cluding the SVG in the object element.

 However, Safari and Chrome, probably because of the shared core, fire the window.onload event handler before the SVG has finished loading. In the example code, the object is accessed in script after it has loaded; the object.on load event handler is then accessed to get the SVG document and assigned the function to the onclick event handler.

JAVA SCRIPT- Adding JavaScript to SVG

Adding JavaScript to SVG


Problem

You want to add JavaScript to an SVG file or element. 

Solution

JavaScript in SVG is included in script elements, just as with HTML, except with the addition of CDATA markup surrounding the script in case XHTML-sensitive charac‐ ters, such as < and >.

The DOM methods are also available for working with the SVG elements.

Demonstration of JavaScript within an SVG file


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" width="600" height="600">
 <script type="text/ecmascript">
 <![CDATA[
// set element onclick event handler
 window.onload=function () {
 var square = document.getElementById("square");
 // onclick event handler, change circle radius
 square.onclick = function() {
 var color = this.getAttribute("fill");
 if (color == "#ff0000") {
 this.setAttribute("fill", "#0000ff");
 } else {
 this.setAttribute("fill","#ff0000");
 }
 }
 }
 ]]>
 </script>
 <rect id="square" width="400" height="400" fill="#ff0000"
 x="10" y="10" />
</svg>


EXPLAIN

As the solution demonstrates, SVG is XML, and the rules for embedding script into XML must be adhered to. This means providing the script type within the script tag, as well as wrapping the script contents in a CDATA block. If you don’t have the CDATA section, and your script uses characters such as < or &, your page will have errors, because the XML parser treats them as XML characters, not script.

The DOM methods, such as document.getElementById(), aren’t HTML specific; they’re usable with any XML document, including SVG. What’s new is the SVG-specific fill attribute, an attribute unique to SVG elements, such as rect. 

The code in the solution is a standalone SVG file, with a .svg extension. If we were to embed the SVG within an HTML file, , the color-changing animation would work the same. The CDATA section is removed because all modern browsers understand the SVG is now in an HTML context. If the file is XHTML, though, add them back.

SVG element , embedded into an HTML page





<!DOCTYPE html>
<html>
<head>
<title>Accessing Inline SVG</title>
<meta charset="utf-8">
</head>
<body>
<svg width="600" height="600">
 <script>
 // set element onclick event handler
 window.onload=function () {
 var square = document.getElementById("square");
 // onclick event handler, change circle radius
 square.onclick = function() {
 var color = this.getAttribute("fill");
 if (color == "#ff0000") {
 this.setAttribute("fill","#0000ff");
 } else {
 this.setAttribute("fill","#ff0000");
 }
 }
 }
 </script>
 <rect id="square" width="400" height="400" fill="#ff0000"
x="10" y="10" />
</svg>
</body>
</html>

Using SVG Libraries

There aren’t quite as many libraries for working with SVG as there are for working with Canvas, but the ones that exist are very handy. One of the most popular is the D3 library, . 

Three other popular libraries include the granddaddy of the SVG libraries, Raphaël, and the newer Snap.svg and SVG.js. All three can simplify SVG cre‐ ation and animation. You can even use Raphaël in both jsBin and jsFiddle, . The following code snippet shows an example of using Raphaël:


// Creates canvas 320 × 200 at 10, 50
var paper = Raphael(10, 50, 320, 400);
// Creates circle at x = 150, y = 140, with radius 100
var circle = paper.circle(150, 140, 100);
// Sets the fill attribute of the circle to red (#f00)
circle.attr("fill", "#f0f");
// Sets the stroke attribute of the circle to white
circle.attr("stroke", "#ff0");

JAVA SCRIPT - Creating a Dynamic Line Chart in Canvas

Creating a Dynamic Line Chart in Canvas


Problem

You want to display a line chart in your web page, but the data changes over time, and you want to dynamically update it. 

Solution

Use the canvas element and the path method to create the chart. When the data changes, update the chart:

var array1 = [[100,100], [150, 50], [200,185],
 [250, 185], [300,250], [350,100], [400,250],
 [450, 100], [500,20], [550,80], [600, 120]];
var imgcanvas = document.getElementById("imgcanvas");
if (imgcanvas.getContext) {
 var ctx = imgcanvas.getContext('2d');
 // rect one
 ctx.strokeRect(0,0,600,300);
 // line path
 ctx.beginPath();
 ctx.moveTo(0,100);
 for (var i = 0; i < array1.length; i++) {
 ctx.lineTo(array1[i][0], array1[i][1]);
 }
 ctx.stroke();
}

EXPLAIN


Canvas paths are the way to create arbitrary shapes in Canvas. After getting the canvas context, ctx, the path is begun with a call to ctx.beginPath(), which begins a new Canvas path. The next line of code is ctx.moveTo, which moves the drawing “pen” to a beginning location, but without drawing. From that point, several lineTo() calls are made using an array of paired values representing the x,y location for each line endpoint. 

After the path has been defined, it’s drawn. We’re not creating a closed path, so I’m not using ctx.closePath(), which would draw all the defined lines and then attempt to draw a line from the ending point to the beginning point. Instead, I’m drawing the line given the points that have been defined, using ctx.stroke(). 

The appearance of the drawing is influenced by two Canvas settings: strokeStyle and fillStyle. The strokeStyle setting sets the color for the outline of a drawing, while the fillStyle does the same for the drawing filling: 


ctx.strokeStyle="black";
ctx.fillStyle="#ff0000;

Any CSS setting will do, or you can use a CanvasGradient or CanvasPattern. You can use the rgba setting to add transparency:

ctx.fillStyle="rgba(255,0,0,0.5)";

You can also use the globalAlpha setting to set the transparency for any drawing that follows:


ctx.globalAlpha = 0.2;

You can further control the appearance of the drawing outline by changing the stroke’s line width:

ctx.line

To dynamically update the chart, you can incorporate timers, and either replace the path (by creating an entirely new context, which would erase the old), or add the new line chart to the same chart.

 shows a web page that creates the line in the solution and then creates two others, each drawn after a short period of time using timers. The colors for the stroke path are changed between lines.

Using timers to dynamically update a line chart


<!DOCTYPE html>
<head>
<title>Canvas Chart</title>
<meta charset="utf-8" />
</head>
<body>
<canvas id="imgcanvas" width="650" height="350">
<p>Include an image that has a static representation of the chart</p>
</canvas>
<script>
 var points = [[[100,100], [150, 50], [200,185],
 [250, 185], [300,250], [350,100], [400,250],
 [450, 100], [500,20], [550,80], [600, 120]],
 [[100,100], [150, 150], [200,135],
 [250, 285], [300,150], [350,150], [400,280],
 [450, 100], [500,120], [550,80], [600, 190]],
 [[100,200], [150, 100], [200,35],
 [250, 185], [300,10], [350,15], [400,80],
 [450, 100], [500,120], [550,80], [600, 120]]];
 var colors = ['black','red','green'];
 var imgcanvas = document.getElementById("imgcanvas");
 if (imgcanvas.getContext) {
 var ctx = imgcanvas.getContext('2d');
// rectangle wrapping line chart
 ctx.strokeRect(0,0,600,300);
 points.forEach(function(element, indx, arry) {
 setTimeout(function() {
 // set up beginning
 ctx.beginPath();
 ctx.moveTo(0,100);
 ctx.strokeStyle = colors[indx];
 for (var i = 0; i < element.length; i++) {
 ctx.lineTo(element[i][0], element[i][1]);
 }
 ctx.stroke();
 }, indx * 5000);
 });
 }
</script>
</body>

Simplify Your Canvas Charts Using a Library

It doesn’t have to be difficult to create a chart using Canvas from scratch, but why walk the steps taken by others? There are several excellent libraries that can simplify not only chart making but other Canvas effects. Over 50 libraries for chart making are listed in a TechSlides Page, including the in‐ creasingly popular D3, . 

Most of the libraries are freely available, though some do charge a fee for commercial use. One of the libraries, Highcharts, even provides demonstrations that you can edit in jsFiddle, making it easy to try out the library’s capability. 

It’s dependent on jQuery, reducing the code to an absurdly simple level. As an example, one of the demonstrations is for a very professional line chart, with plot lines and labels,. Yet the code to create this example is equivalent to that in the following code block, which I modified to feature my own locations and temperature metric, which you can try yourself at jsFiddle: 


$(function () {
 $('#container').highcharts({
 title: {
 text: 'Monthly Average Temperature',
 x: -20 //center
 },
 subtitle: {
 text: 'Source: Weather.com',
 x: -20
 },
 xAxis: {
 categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
 },
 yAxis: {
 title: {
 text: 'Temperature (°F)'
 },
 plotLines: [{
 value: 0,
 width: 1,
 color: '#808080'
 }]
 },
 tooltip: {
 valueSuffix: '°F'
 },
 legend: {
 layout: 'vertical',
 align: 'right',
 verticalAlign: 'middle',
 borderWidth: 0
 },
 series: [{
 name: 'Seattle, WA',
 data: [47,51,55,59,65,70,75,75,70,60,52,47]
 }, {
 name: 'Grand Isle, VT',
 data: [27,31,40,54,67,76,81,79,71,57,45,33]
 }, {
 name: 'St. Louis, MO',
 data: [40,45,55,67,77,85,89,88,81,69,56,43]
 }]
 });
 });


Not only is the plotted chart professional looking, it’s zoomable, which means you can move your mouse cursor over the chart to examine the plot points in detail. That level of interactivity isn’t necessarily trivial in Canvas, because one of the downsides to Canvas is the fact that you can’t attach event handlers to the individual elements of Canvas— only to the Canvas area itself.

Not being able to attach an event to individual elements means that you’ll have to keep track of where the mouse is, and what’s underneath it at any point in time

Java Converting Epoch Seconds to DMYHMS

Java Converting Epoch Seconds to DMYHMS

Problem

You need to convert a number of seconds since 1970 into a Date .

Solution

Just use the Date constructor.

Explained

“The Epoch” is the beginning of time as far as modern operating systems go. Unix
time, and some versions of Windows time, count off inexorably the seconds since
the epoch. On systems that store this in a 32-bit integer, time is indeed running out.
Let’s say we wanted to find out when the Unix operating system, whose 32-bit ver-
sions use a 32-bit date, will get into difficulty. We take a 32-bit integer of all ones,
and construct a Date around it. The Date constructor needs the number of millisec-
onds since 1970, so we multiply by 1,000:

/** When does the UNIX date get into trouble? */
public class Y2038 {
public static void main(String[] a) {
// This should yield 2038AD, the hour of doom for the
// last remaining 32-bit UNIX systems (there will be
// millions of 64-bit UNIXes by then).
long expiry = 0x7FFFFFFFL;
System.out.println("32-bit UNIX expires on " +
Long.toHexString(expiry) + " or " +
new java.util.Date(expiry * 1000));
}
}


Sure enough, the program reports that 32-bit Unixes will expire in the year 2038 (you might think I knew that in advance if you were to judge by the name I gave the class; in fact, my web site has carried the Y2038 warning to Unix users for several years now). At least Unix system managers have more warning than most of the gen- eral public had for the original Y2K problem.

> java Y2038
32-bit UNIX expires on 7fffffff or Mon Jan 18 22:14:07 EST 2038
>

At any rate, if you need to convert seconds since 1970 to a date, you know how.

JAVA SCRIPT - Using a Timer to Automatically Update the Page with Fresh Data

Using a Timer to Automatically Update the Page with Fresh Data


Problem

You want to display entries from a file, but the file is updated frequently. 

Solution

Use Ajax and a timer to periodically check the file for new values and update the display accordingly. The Ajax we use is no different than any other Ajax request. We’ll use a GET, because we’re retrieving data.

 We put together the request, attach a function to the onreadysta techange event handler, and send the request: 


var xmlhttp;
// prepare and send XHR request
function populateList() {
 var url = 'text.txt'; // change to full url to prevent caching problems
 xmlhttp.open('GET', url, true);
 xmlhttp.onreadystatechange = processResponse;
 xmlhttp.send(null);
}

In the code that processes the response, we just place the new text into a new unordered list item and append it to an existing ul element:

// process return
function processResponse() {
 if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
 var li = document.createElement("li");
 var txt = document.createTextNode(xmlhttp.responseText);
 li.appendChild(txt);
 document.getElementById("update").appendChild(li);
 setTimeout(populateList,15000);
 } else if (xmlhttp.readyState == 4 && xmlhttp.status != 200) {
 console.log(xmlhttp.responseText);
 }
}

The new part is the addition of the setTimeout() in the code. It triggers the entire process again in 15 seconds.The process is started by creating the xmlHttpRequest object in the Window load event handler, and then calling populateList() the first time:

window.onload=function() {
 xmlhttp = new XMLHttpRequest();
 populateList();
}


EXPLAIN

The fact that we’re doing a direct request on a static text file might be new, but remember that a GET request is more or less the same as the requests we put into the location bar of our browsers. If something works in the browser, it should successfully return in an Ajax GET request…within reason. 

The key to using timers with Ajax calls is to make sure that the last call is completed before making the next. By adding the call to setTimeout() at the end of the Ajax call, we trigger the timer when we know an outstanding request isn’t being processed. We can also put in a check for the request status, and cancel the timer event altogether if we’re concerned about hitting a failing service, over and over again. When I ran the application that included the solution code, 

I changed the text file by using the Unix echo command: 


$ echo "This is working" > text.txt