code prettify

Thursday 20 November 2014

How to draw a smiley cookie face using html5 canvas?

How to draw a smiley face as shown below using html5 canvas.
Well, it's not as complicated as it looks. The picture includes below parts:

1. outer face circle
2. two circular eyes
3. one straight line nose
4. a smile arc

The above basic parts can be drawn using arc and moveTo methods of context object and it involves a little calculation as to where to place the sub parts so as to sync the whole face symmetrically.

Code:

<canvas id="smiley" width="800" height="600">

<script>
    drawSmiley();

    function drawSmiley() {
        var canvas = document.getElementById("smiley");
        var context = canvas.getContext("2d");

        // Draw outer face circle
        context.beginPath();
        context.arc(300, 300, 100, 0, degreesToRadians(360), true);
        context.fillStyle = "#ffffcc";
        context.fill();
        context.stroke();

        // Draw left eye circle
        context.beginPath();
        context.arc(250, 270, 15, 0, degreesToRadians(360), true);
        context.stroke();

        // Draw right eye circle
        context.beginPath();
        context.arc(350, 270, 15, 0, degreesToRadians(360), true);
        context.stroke();

        // Draw straight line nose
        context.beginPath();
        context.moveTo(300, 285);
        context.lineTo(300, 330);
        context.stroke();

        // Draw smile arc
        context.beginPath();
        context.arc(300, 330, 55, degreesToRadians(20), degreesToRadians(160), false);
        context.stroke();
    }

    function degreesToRadians(degrees) {
        return (degrees * Math.PI) / 180;
    }
</script>

I know the face looks a little out of place but you can do it better I know ;)

Click here for a demo.

How to draw a quarter circle arc using canvas?

Using canvas, we can draw a circle or a circular arc using the arc method of the context object.

The basic syntax of the arc method is:

context.arc(x, y, radius, start_angle, end_angle, direction)

Parameters:
x, y              are the center point co-ordinates
radius          (of the arc)
start_angle  Position where the arc should start (in radians)
end_angle   Position where the arc should end (in radians)
direction     Whether to start tracing in clockwise or anti-clockwise direction.  (bool)
                   true indicates anti-clockwise and false indicates clockwise direction.

So one can modify the start_angle, end_angle and the direction to trace any part of a circle. To draw a quarter circle arc, we need to start at 0 degree and end at 270 degrees but we need to trace in anti-clockwise direction so direction value would be true.

Relationship between radian and degrees:

2 * Pi  Radians = 360 degrees

Code for a quarter-circle arc:

<canvas width="600" height="400"></canvas>
<script>
    var canvas = document.getElementsByTagName("canvas")[0];
    var context = canvas.getContext("2d");

    context.beginPath();
    context.arc(100, 100, 75, 0, degreesToRadians(270), true);
    context.stroke();

    function degreesToRadians(degrees) {
        return (degrees * Math.PI) / 180;
    }
</script>


Click here for a demo.


How to draw a triangle using Canvas?

Canvas is basically a space in the web page where you draw graphics using javascript. Everything on a canvas is all about canvas.

So to start, lets have a canvas space over a 600 x 400 pixel area.

<canvas width="600" height="400">

The next thing we need to do is get a reference to the canvas element and get a context reference to it. Context is basically an object with methods and properties that allows us to draw on the canvas.

To draw a triangle, we basically have to start at a point and proceed along a line then move on to another point tracing along the path as we do so. The basic point is to first create a path and then stroke or fill it, so as to make it visible.

Below is the code to draw a triangle on a canvas:

<script>
    // Get dom reference to canvas element
    var canvas = document.getElementsByTagName("canvas")[0];

    // Get context reference to canvas
    var context = canvas.getContext("2d");

    // Begin a path with beginPath() method
    context.beginPath();
    context.moveTo(100, 150);

    // Traces a line path from current point to specified point
    context.lineTo(250, 75);
    context.lineTo(125, 30);

    // Closes the path by joining from current point to point where
    // path began first
    context.closePath();
    context.lineWidth = 5; // Sets the line width

    // Make the path visible by stroking it
    context.stroke();

    // Fill inside of the closed path structure with color
    context.fillStyle = "red";
    context.fill();
</script>


Click here to see a demo.

Monday 17 November 2014

HTML5 CANVAS Bring out the inner artist in us

It's time to get our hands dirty with some colors and bring out the inner artist and creationist within us to fore. HTML5's CANVAS element provides us with a virtual canvas which is similar to the leather canvas which real world painters and artists use to draw wonderful art and what not.

Some use cases to which the CANVAS element can help us in:
1. To create a simple drawing structure like a circle, ellipse which may be part of a larger design.
2. To create an animation of written letters created slowly to create an illusion of an invisible hand writing.
3. To create html5 based games based on the idea of "update and loop" principle and "persistence of vision" concept.
4. To develop a platform for real-time creation of structures like charts, hierarchical box shaped structures one beneath other etc.

There are many more of which I am ignorant right now, but will update as soon as I know about it.

Stay tuned as we begin our journey as an artist, thinker, designer, creationist and what not :)

Tuesday 28 October 2014

Handling errors while using html5 audio


While using the <audio> tag, there are chances of errors happening while playing the audio file.

It may be due to one of the below reasons:
- Intermittent connectivity
- Invalid "src" being set
- An audio format which the browser cannot decode and so cannot play
- Due to corrupted audio file being played

It would be better if we could know about these and be prepared to handle them instead of putting the user through a very bad experience.

The audio object has an error event which can be listened to for any errors. The "audio" attribute on the audio element can also be accessed to get the last error which had occurred. It returns a "MediaError" object representing the current error state of the element. It returns null if there is no error.

Types of error:
Each of the below error types has a corresponding associated number that is the error code produced by the "event".

- MEDIA_ERR_ABORTED(1)
    Occurs when the fetching process for the media resource was aborted by the user agent (browser) at the user's request.
    
- MEDIA_ERR_NETWORK(2)
    A network error of some description caused the user agent (browser) to stop fetching the media resource (after the resource was established to be usable).

- MEDIA_ERR_DECODE(3)
    An error of some description occurred while decoding the media resource (after the resource was established to be usable).

- MEDIA_ERR_SRC_NOT_SUPPORTED(4)
    The media resource indicated by the src attribute or assigned media provider object was not suitable.

Sample Code:
<audio src="sample.mp3"></audio> 
<script>     
    var audioElem = document.document.getElementsByTagName("audio")[0];
    
    // Add event to detect error and display error code      
    audioElem.addEventListener("error", function () {
        if (audioElem.error) {
            alert(audioElem.error.code);
        }
    }, false);
</script> 

References:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events#Error_handling
https://html.spec.whatwg.org/#error-codes

Sunday 26 October 2014

Assessing HTML5 audio Playback Capabilities using canPlayType method

Assessing <audio> Playback Capabilities

We can test if a particular format of audio can be played by the browser by using the "canPlayType" method of the audio object.

Basically, "canPlayType" method takes an audio format and returns a string that suggests / represents how confident the browser feels that it can play that type of audio.

Below are 3 results from "canPlayType" method:
- "" (Empty string -> cannot play)
- maybe (might be able to)
- probably (browser is reasonably confident that it can play)

Some caution is required when trying to select media in this way, because browsers differ in their way of assessing their ability to play a format.

The different ways in which support is assessed means that the canPlayType method should be used very carefully. A better alternative to it is to provide audio files in more than one format as <source> options.

Example Code:

<audio id="media" controls preload="metadata">
    Audio cannot be played
</audio>
<table id="info" border="1">
    <tr><th>Property</th><th>Value</th></tr>
</table>
<script>
    var mediaElem = document.getElementById("media");
    var tableElem = document.getElementById("info");

    // List of audio files which can be provided for playing
    var mediaFiles = ["sample.ogg", "sample.wav", "sample.mp3"];
    var mediaTypes = ["audio/ogg", "audio/wav", "audio/mp3"];

    // Loop through the audio type list
    // and determine the type which can be played by the browser
    // and set the "src" to it
    for (var i = 0; i < mediaTypes.length; i++) {
        var playable = mediaElem.canPlayType(mediaTypes[i]);

        // if "playable" is empty, then browser can not play the
        // audio format
        if (!playable) {
            playable = "no";
        }

        tableElem.innerHTML += "<tr><td>" + mediaTypes[i] 
            + "</td><td>" + playable + "</td></tr>";

        if (playable == "probably") {
            mediaElem.src = mediaFiles[i];
        }
    }
</script>

In the above example, we are looping through all the audio formats and displaying the info in a table related to whether the browser can play the audio or not. While doing so we are also setting the "src" attribute to audio file which can be played by the browser.

Tuesday 14 October 2014

How to convert audio files from one format to another using "Sound Converter"?

Sound Converter is an open source tool available from Ubuntu Software Center that can be used to convert audio files from one format to another.

Example usage is to generate different formats of same audio file to be used in case of HTML5 <audio> element.


Install it from Ubuntu Software Center



Add a file to be converted, from the browser dialog after clicking on "Add File"


Select the format, the audio file is to be converted to and the place to be saved and then click the "Convert" button in the main window to begin the process.








How to play a series of audio files using HTML5 audio element?

By default the HTML5 <audio> tag allows us to play any one audio file at a time. How do we go about playing a series of audio files that are related but are present separately, lets say something like intro.mp3, part1.mp3, part2.mp3, conclusion.mp3 (something part of our presentation) ?

Well, this can be done with a little bit of coding using the following apis from <audio> element:
- "src" property
- "load" and "play" methods
- "ended" event

Logic:
It goes something like this. We play our first audio file, and then wait or listen for the "ended" event and as soon as it is fired, we change the "src" attribute of <audio> element to our next audio file and call the "load" method to load the file and then call "play" event to play the next audio. This continues for other audio files until we complete all the audio files and then again start from beginning if required.

Code:

<!-- audio element to play our audio files -->
<!-- Notice there is no "src" attribute defined -->
<audio controls id="audio"></audio>


<script>
    var position = 0; // Store position of audio currently playing
    var audioList;    // Store array list of audios to be played
    var audio;        // Store reference to the <audio> element

    window.onload = function () {
        // List of audio files to be played
        audioList = [
            "intro.mp3",
            "part1.mp3",
            "part2.mp3",
            "conclusion.mp3"
        ];

        // Reference to the <audio> element
        audio = document.getElementById("audio");

        // Attach listener to the "ended" event
        audio.addEventListener("ended", nextAudio, false);


        // Play the first audio file when the page loads first time
        playAudio();

    };

    // Handler function to be called when "ended" event is 
    // called on <audio> element that is when the audio files
    // reaches its end
    function nextAudio() {
        // Increase the position to indicate playing next audio file
        position++;

        // If we have reached the end of the list, then start
        // playing from first audio again
        if (position >= audioList.length) {
            position = 0;
        }

        // Play the next audio
        playAudio();
    }

    // Plays the currently positioned audio file
    function playAudio() {
        // Set the "src" of the current audio file, load and play it
        audio.src = audioList[position];
        audio.load();
        audio.play();
    }
</script>

Monday 13 October 2014

First prototype of HTML5 Audio Player launched

Hi all, we have now started ahead with our first prototype for "the html5 audio player". Please refer the below image:



Currently, we just have the play, pause and volume increase, decrease functionality.

A lot more needs to be done in terms of functionality, design and usability. Looking forward to ideas and help :)

Future plan:
- To include a progress bar to show the progress of the audio
- To manually control the progress by clicking the progress bar

Fork at https://github.com/satejkumar/html5_audio_player.git

How do you know you have reached the end of an HTML5 audio?

It is very useful to know when an audio file has reached its end in the browser to indicate it visually.

To do so, we can attach an "ended" event on the HTML5 audio element, which happens when the audio reaches the end and stops playing. Using javascript, we can listen to this event and take necessary action.

Example:

<audio id="sample_audio" src="sample.mp3"></audio>

<script>
    var audio_elem = document.getElementById("sample_audio");

    audio_elem.addEventListener("ended", function() {
        alert("The audio file has finished playing");
    });
</script>