Creating a Multiple Choice Quiz in HTML5



What you will learn:

  • how to build a quiz using HTML5
  • how to use the canvas element
  • how to use randomization in a quiz
  • how to track a quiz score
  • how to import data from an xml file (optional)

Prerequisites:

  • basic knowledge of Javascript or other coding language
  • access to a server (to import data from xml via php)

Notes
So here we go. We want to make a quiz in HTML5 where the options are randomized. For maximum reusability, we might want to import our questions from an XML file. I will leave the xml part to last, so that it’s optional.

To write our HTML5 code, we don’t need any fancy software – any text editor will do: WordPad or NotePad. I’m using TextPad, which you can download from here: http://www.textpad.com/products/textpad/index.html

Remember than HTML5 won’t work in older browsers, especially Internet Explorer. I’m using Google Chrome Version 18. You will need a modern browser for testing. The last, and optional, part of the tutorial requires php, so you will need a server to test it.

* You can view a working example here and download the completed source files here

 

Step 1

Open your text editor and type:

 <!DOCTYPE HTML>

This is the way that we begin all of our HTML5 documents. Now let’s fill out the document structure:

<!DOCTYPE HTML>

<head>
    </head>
    <body>
    </body>
</html>

Save the document as quiz.html

Now, one of the great features of HTML5 is that we can use a page element called <canvas> to draw things directly on the page – and then redraw them. This means that we can do simple animations and create multimedia interactions, such as we do in Adobe Flash. The user will be able to take our quiz without having to refresh the page – this small thing makes a big difference in usability.

So that we can focus on using the canvas element, we want to keep the rest of our webpage as simple as possible. I’m using a skyblue backround with a few polka dots. So in the <head> tags, I add:

<style>
    body {
          background-image:url('BG.png');
         }
</style>

For this code to work, the image file BG.png must be in the same folder as our main file quiz.html. To keep it simple, we won’t be using a CSS file and everything will be in the same folder.

You can get BG.png and the other art assets for this project here

You don’t need to use the same background art, but please don’t use a white background because we will be using some white images and we need them to show up properly.

Test out what you have so far by opening quiz.html in a browser, instead of the text editor.



Step 2

Let’s finish the html and styling before we start on the javascript code.

Inside the body of the web page, add:

 <body>
    <div id="ccontainer">
        <canvas id="myCanvas" width="550" height="400"> </canvas>
    </div>
</body>

What we did here was to create a holding element called #ccontainer, which we will use to center our content on the page. Then we created a canvas element with the reference id: myCanvas, width 550 pixels and height of 400 pixels. We need to specify the dimensions here, or it will be assigned the default dimensions 300 x 150.

Okay, back to the <style> tags and add the following:

#ccontainer{
            width:550px;
            margin: 0 auto;
            margin-top:100px;
            }
                                 
#myCanvas {
            //background:#FFFFFF;
            }

Following the eariler code, our quiz is going to be 550 x 400 pixels in size, centered on the page (margin: 0 auto;) and it’s going to be 100 pixels from the top of the page (for aesthetics, or so you can later add a page title or even Google ads).

The line background:FFFFFF; is commented out. If you activate it temporarily, you will be able to see the position of the canvas on the page. Otherwise, the canvas is invisible to us – it is empty at this time. Once commented out, this styling element is redundant, but if you reuse the code for your own purposes, you may want to add padding or a colored background.

 

Step 3

Now that the elements of the page are all in place, let’s get to the javascript.

Inside the <head> tag, add the following:

<script>
      window.onload = function(){                                                      };//windowonload
</script>

All of our javascript will be contained in the window.onload function and it will run when the page loads.

What I always like to do first in a project is declare all my variables. Here we go then:

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var quizbg = new Image();
var Question = new String;
var Option1 = new String;
var Option2 = new String;
var Option3 = new String;
var my=0;
var CorrectAnswer = 0;
var qnumber = 0;
var rightanswers=0;
var wronganswers=0;
var QuizFinished = false;
var lock = false;                
var textpos1=45;
var textpos2=145;
var textpos3=230;
var textpos4=325;        

First we declared our canvas by referencing the element id we used earlier (the name MUST match the name used in the html.)

Next we set the ‘context’ of the canvas. It will be “2d”, obviously, not 3d. We need the context of the canvas to draw on it.

We will only need one image for this quiz, so we will declare the image as ‘quizbg’.

We need four strings: Question and Option1 – 3. You can guess that these will hold the questions and answers to the quiz.

The variable my will be used to reference mouseclick coordinates. Our variable CorrectAnswer will be used to hold the reference to the correct answer – 1,2 or 3 corresponding to multiple choice option 1, 2 or 3.

We then use qnumber to track the current question number. Two variables called rightanswers and wronganswers will help us to calculate the score by storing the number of questions that the user got right and wrong.

QuizFinished will help us to track when the quiz is complete.

Next we have a boolean variable lock. This variable will help us to ‘lock’ the answers so that the user can’t click on them more than once.

Finally, we have the textpos variables. With the canvas element, we need to ‘draw’ the text, and it is very important to keep track of the position of everything we draw. The numbers don’t mean anything yet; we will refer back to them later.

Okay, so much work and we don’t even have anything on the screen yet! Let’s remedy that in step 4…

Step 4

In the source file (at www.flashbynight.com/tutes/html5quiz/1/version1.zip), you will notice that, apart from the background image, we only have one more image: quizbg.png. This contains three graphics that we wish to use: the background for the quiz, the tick for a correct answer and the cross for a wrong answer. Notice that the image is 550 x 470 pixels, whereas our canvas is only 550 x 400 pixels. This means that the tick and cross will not be visible on our canvas, but we can ‘slice’ them off and use them separately, as we will see in Step 8. This way, we only use one graphic and we don’t need to check whether three separate graphics have loaded.

Right after the previous code, add the following lines:

quizbg.onload = function(){
        context.drawImage(quizbg, 0, 0);
}//quizbg
quizbg.src = "quizbg.png";

This function draws our image onto the canvas, when it is loaded. Note the syntax:

                context.drawImage(ImageName, x, y);

…where ImageName is the reference to the image and x,y are the coordinates from the top left of the canvas.

Refresh your browser and you should see this:

 

img1

 

Now, because we need to ‘draw’ the text onto the canvas, we need to be very particular about the coordinates. We need to know how far across to begin writing the text, the y-position for the middle of each or our four boxes, where we want our feedback message to appear, where to reference the cross/tick images and where we want our cross/tick to appear.

These coordinates are mapped as follows:

img2

Notice that the numbers down the right-hand side are the variables textpos1-4 that we defined earlier.

 

Step 5

This is a quiz, right? So we’re going to need questions. We will start by storing our questions in array form (later we will read them from xml instead).

So we can have two arrays (place these lines of code following the other variables for easy access):

var Questions = ["Where is Paris?","Where is London?","Where is Rome?"];
var Options = [["France","Belgium","Norway"] ,["England","China","Denmark"], ["Italy","Brazil","Canada"]];

We have three questions here, but we can add more questions easily by filling out the arrays further. For easy reference, the first answer in each set is always the correct one. Then we will randomise the options at the point where we draw them on the screen.

Arrays are always zero-referenced. Hence to refer to the first question, we use: Questions[0] and the second question is Questions[1] and so on.

The answers are stored in an array of arrays. Hence to refer to answer 1, set 1, we use Options[0][0], answer 2, set 1 is  Options[0][1] and so on.

Step 6

We will create a function called SetQuestions to select questions and draw them on the canvas.

We only want to load up the first set of questions when we know our background image is loaded, so we will call the function from our previous function, which should now be:

quizbg.onload = function(){
        context.drawImage(quizbg, 0, 0);
        SetQuestions();
}//quizbg
quizbg.src = "quizbg.png";

Immediately after that, we can write our SetQuestions function:

SetQuestions = function(){
                                                             
       Question=Questions[qnumber];
                                 CorrectAnswer=1+Math.floor(Math.random()*3);                                         
         if(CorrectAnswer==1){Option1=Options[qnumber][0];Option2=Options[qnumber][1];Option3=Options[qnumber][2];}               
         if(CorrectAnswer==2){Option1=Options[qnumber][2];Option2=Options[qnumber][0];Option3=Options[qnumber][1];}               
         if(CorrectAnswer==3){Option1=Options[qnumber][1];Option2=Options[qnumber][2];Option3=Options[qnumber][0];}
                                                                }//SetQuestions

Line by line: First we select the current question from the array, and assign it to the string variable Question. Next, we select a random number, from 1 to 3 and assign it to CorrectAnswer. We will set up the options in such a way that CorrectAnswer refers to the option with the correct answer.

Programmers don’t like to add multiple lines of code on one line, but here, I think it makes it easy to read because of the parallelism. Depending on the random variable, we assign Option1, Option2 and Option3. Remember Options[qnumber][0] will always hold the correct answer, because we put the correct answer first in each case. Hence, if CorrectAnswer==1, the correct answer will be the first option, if CorrectAnswer==2, the correct answer will be the second option and so on.

Now, still inside the SetQuestions function, add the following lines:

context.textBaseline = "middle";
context.font = "24pt Calibri,Arial";
context.fillText(Question,20,textpos1);
context.font = "18pt Calibri,Arial";
context.fillText(Option1,20,textpos2);
context.fillText(Option2,20,textpos3);
context.fillText(Option3,20,textpos4);

 

The first line makes sure that the coordinates that we give will match to the middle of the text; we want the text to be nicely centered in our boxes. Other possible values, apart from ‘middle’ are: tophangingalphabetic, ideographic, and bottom.

Next, we set the font for the question to 24pt Calibri, or Arial if Calibri is not available on the user’s browser.

Then we use context.fillText to place our Question text 20 pixels from the right and 45 pixels (textpos1=45) from the top of the canvas.

We set a smaller font for our options and then place the rest of the text.

Open the document in your browser and you should see the following:

 

 

img3

Refresh your browser a couple of times and see what happens. The options will appear in different positions.

 

Step 7

Our next step is to allow the user to click on the options and to give feedback as to whether they got the answer correct or wrong.

To do that, we need to add a ‘listener’ to the canvas. Our listener will simply listen out for a mouseclick and then act on it. Unlike Flash, we can’t add a listener to a specific object. We need to listen for a click on the canvas and then use the x,y coordinates of the mouseclick to figure out what has been clicked on. A bit troublesome, I know, but we can do it.

After our SetQuestions function, let’s add this line:

canvas.addEventListener('click',ProcessClick,false);

This will listen for a mouseclick and call the function ProcessClick(). Now:

function ProcessClick(ev) {                
       my=ev.y-canvas.offsetTop;
       if(ev.y == undefined){
       my = ev.pageY - canvas.offsetTop;
       }
//more code to go here
}//ProcessClick

 

The mouseclick ‘event’ is referenced by ‘ev’. We use my to store the mouseclick y-coordinate and we need to use offsetTop to make sure we have the coordinates relative to the canvas and not relative to the entire web page. This currently works in all browsers except Firefox. Firefox doesn’t recognise ev.y and requires us to use ev.pageY instead. So we add a couple of lines to do it the Firefox way. Unfortunately, there are currently elements of HTML5 that work differently in different browsers. On the positive side, this is the only cross-browser issue we will face in this particular tutorial.

 

Once we ‘hear’ the click, we need to find out what has been clicked on unless the question has already been answered, in which case, we want the user click to move us onto the next question.

In pseudocode:

if (the question has been answered){go to the next question;}

else{

if (option 1 was clicked){check if option 1 is the right answer;}
if (option 2 was clicked){check if option 2 is the right answer;}
if (option 3 was clicked){check if option 3 is the right answer;}
}

Now for the actual code. Replace the line //more code to go here with:

if(lock){
        ResetQ();
}//if lock
else{
        if(my>110 && my<180){GetFeedback(1);}
        if(my>200 && my<270){GetFeedback(2);}
        if(my>290 && my<360){GetFeedback(3);}
}//!lock

Where do we get the numbers here? Observe the figure below and you will see that they correspond with the coordinates of the boxes that hold the answers. Since the boxes stretch all the way across the canvas, the x coordinates don’t matter to us.

 

img4

It would be better coding practice to calculate the positions based on the variables we used earlier (textpos1 etc), but let’s just keep our code as simple as possible.

You can see that we use the variable ‘lock’ to determine whether the question has been answered or not. We will need to write a function called ResetQ to reset the question. For now, let’s just create an empty function so as not to get an error:

ResetQ= function(){}

You can also see that we need to create a function called GetFeedback to check the user’s answer. According to the code above, we pass it the parameter 1 if option 1 was chosen, 2 if option 2 was chosen etc. Let’s work in this in Step 8:

 

Step 8

Here is our GetFeedback() function:

GetFeedback = function(a){
                                 
        if(a==CorrectAnswer){
                context.drawImage(quizbg, 0,400,75,70,480,110+(90*(a-1)),75,70);
                rightanswers++;
        }             
        else{
                context.drawImage(quizbg, 75,400,75,70,480,110+(90*(a-1)),75,70);
                wronganswers++;
        }
        context.font = "14pt Calibri,Arial";
        context.fillText("Click again to continue",20,380);
        lock=true;
}//get feedback

 

Let’s go through it line by line. The ‘a’ variable when we call the function corresponds to the variable passed to the function earlier. It will be 1,2 or 3 depending on which option was clicked. Now, if you look back to step 6, the variable CorrectAnswer holds the correct answer. Hence if a==CorrectAnswer then the answer is correct. Otherwise (else) the answer is wrong.

Now, if the answer is correct, we want to take our original image and ‘slice’ off the tick graphic and place it on the screen. We can do this using the full parameters of the drawImage function, which are:

drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

Looks confusing, huh? Where you see ‘s’, think ‘source’ and where you see ‘d’, think ‘destination’. Let’s explain it with a graphic:

 

img5

So sx is the x coordinate of the source, sy is the y coordinate of the source. sHeight and sWidth are the height and width of the ‘slice’, which is then redrawn according to: dx and dy (the destination coordinates), dWidth and dHeight (the destination dimensions, which usually match the source dimensions. Since dy may vary according to the user’s answer, we need to perform a quick calculation: 110+(90*(a-1)). In fact, we ought to use our initial variables to perform a calculation, therefore making the code more reusable since we only need to change the initial variables. But once again, let’s keep the code easy to read through for now.

The next line: rightanswers++; helps us to keep track of the correct answers, so we can display a final score at the end of the quiz.

The next few lines are very similar and handle a wrong answer by placing the cross instead of the tick and tracking a wrong answer.

Finally, we set the font size to 14 and use fillText() to place a message on the screen at the given coordinates. The text, as we mentioned, is drawn on the screen, so the user will not be able to copy and paste it.

Finally, we set lock=true; This prevents the user from answering the question again. However, if the user clicks the screen again, we want to move on to the next question, using the function ResetQ() which we have left empty for now.

Go ahead and test the quiz in your browser. Try getting a right answer, then refresh your browser and try getting a wrong answer.

 

Step 9

Right then, let’s proceed with ResetQ(), the function which we left empty and which will reset our quiz and move onto the next question:

ResetQ= function(){
        lock=false;
        context.clearRect(0,0,550,400);
        qnumber++;
        if(qnumber==Questions.length){EndQuiz();}
else{
        context.drawImage(quizbg, 0, 0);
        SetQuestions();}
}

Line by line: We begin by unlocking the quiz, so that the user can answer the next question. Then we use clearRect() to clear the entire canvas away (550 and 400 are the canvas dimensions, remember). We then increase the variable qnumber to track which question we are on. If qnumber==Questions.length that means the last question has been reached and we should end the quiz with the function EndQuiz(); Otherwise (else), we need to redraw the quiz background using drawImage() and then call the function SetQuestions(). SetQuestions will take care of everything from here on.

To avoid an error, create the empty function:

EndQuiz=function(){}

…and then test in the browser. You should now be able to cycle through all the questions. After the last one (there are only three in our example), you will get a blank screen. If you keep clicking, the quiz will try to give feedback, which we don’t want, but we can fix that easily in our final step.

Step 10

So we need to write out and explain the EndQuiz() function. Here we go:

EndQuiz=function(){
        canvas.removeEventListener('click',ProcessClick,false);
        context.drawImage(quizbg, 0,0,550,90,0,0,550,400);
        context.font = "20pt Calibri,Arial";
        context.fillText("You have finished the quiz!",20,100);
        context.font = "16pt Calibri,Arial";
        context.fillText("Correct answers: "+String(rightanswers),20,200);
        context.fillText("Wrong answers: "+String(wronganswers),20,240);
}

First we remove the ‘listener’ that we added earlier. After this, clicks on the canvas are no longer recorded. Then we use a variation of our ‘slice’ trick to copy the first translucent box in our quiz background and stretch it down over the whole canvas. Now we have a white translucent background for our final ‘page’.

Next we simply draw our final text messages on the screen, nicely formatted and spaced out. Luckily, we’ve been keeping track of the right and wrong answers, so we can give some useful feedback to the user.

The end of the quiz should look like this:

img6

And there we have it! A fully working quiz in HTML5 using the canvas element.

If something is not working, download the source code from here: www.flashbynight.com/tutes/html5quiz/1/version1.zip and see where you went wrong.

 

Step 11 (slightly more advanced)

So we are finished, but we are not finished. As an extension to the tutorial, I’d like to show how to read the data from an XML file. You can download a working version from www.flashbynight.com/tutes/html5quiz/1/version2.zip.

Why would we want to do this? XML files can be read by php, Flash and other software, meaning you can use one file for many versions. Also, XML is machine AND human readable. I work in an e-learning company and it’s great to keep the data in XML files because even our editors, who don’t know any computer languages, can read and edit it.

First things first, change these lines in the old code:

var Questions = ["Where is Paris?","Where is London?","Where is Rome?"];
var Options = [["France","Belgium","Norway"] , ["England","China","Denmark"] , ["Italy","Brazil","Canada"]];

to:

var Questions = new Array;
var Options = new Array;

…and let’s place the data in an XML file. If you have never written an XML file before, don’t worry, you don’t need any special software. You can do it in WordPad, NotePad, TextPad or any other text editor.

Use your text editor to open a blank document and save it as: data1.xml

Then enter the data as follows and save:

<?xml version="1.0" encoding="ISO-8859-1"?>
<All>        
        <task>
              <question>Where is Paris?</question>
              <option>France</option>
              <option>Belgium</option>
              <option>Norway</option>
        </task>        
        <task>
              <question>Where is London?</question>
              <option>England</option>
              <option>China</option>
              <option>Denmark</option>
        </task>        
        <task>
              <question>Where is Rome?</question>
              <option>Italy</option>
              <option>Brazil</option>
              <option>Canada</option>
        </task>
</All>

 

As you can see, the code is easy for us to read. Each part of the quiz is labeled as a ‘task’ and the questions and options are labeled as such. Again, the first option is the correct answer in each case.

Now we just need a way to read the XML and use the data. For this, we will use the language PHP. This means that you will need to have access to a server to test the following part. Or in other words, you need to be able to upload it to your website.

First things first. If we use PHP on a page, the extension needs to be ‘.php’. So rename the file from ‘quiz.html’ to ‘quiz.php’. Don’t worry, all the javascript and html will still work and we can still use the html5 canvas elements.

What we want to do is this: we want to have a dynamic page, so that we can use the address:

www.website.com/quiz.php?q=1

…to run the quiz using our file data1.xml

or we could use:

www.website.com/quiz.php?q=2

…to load in data2.xml

Can you see how that works? If we use the address ‘www.website.com/quiz.php?q=1’, we are telling the browser to go to the page www.website.com/quiz.php with the variable ’q=1’
accessible by the PHP code. We can control which quiz is loaded by changing the variable q, so now we have a dynamic page.

We only need a few lines of PHP code to do our work. Following the line, var Options = new Array;  add the following:


 
<?php
        $datastr = "data".strval($_GET["q"]).".xml";
        $xml = simplexml_load_file($datastr);
        $counter= count($xml);
        for($i=0;$i<$counter;$i++){                      
           echo "Questions[".$i."]='".$xml-> task[$i]->question ."';";
           echo "\n";
           echo "Options[".$i."]=['".$xml-> task[$i]->option[0] ."','";
           echo $xml-> task[$i]->option[1] ."','";
           echo $xml-> task[$i]->option[2]."'];";
           echo "\n";
        }                                            
?>

 

Looks difficult? Let’s go through the code.

The tags <?php   … ?> indicate that everything within them is PHP code. none of the rest of the document, however, is PHP code.

In PHP, we add a dollar sign to denote a variable, so we define a variable called $datastr. A period in PHP denotes ‘+’, so we are adding “data” PLUS the value of “q” (from the URL) PLUS “.xml”.

In other words, if q=1, $datastr=”data1.xml”;

(If you don’t want a dynamic page, you can just replace this line with $datastr=”data1.xml”;)

The next line loads the XML in a format called ‘simplexml’.

The next line determines the number of ‘children’ of the main node of the XML document and assigns the value to $counter. This corresponds to the number of questions in our quiz.

Now that we know the number of questions, we can use a loop to form the information we need in array format.

The command ‘echo’ in PHP is interesting; its output will be read in HTML, while the rest of the PHP code is ‘invisible’ to the HTML. In this case, because the PHP script is inside the Javascript, its output will be read in Javascript.

So when i=0, the first line of the loop will output:

Questions[0]='Where is Paris?';

…because: xml-> task[0]->question corresponds to the first question; ‘Where is Paris?”. Notice that the XML is very logical and easy to understand.

The line: echo "\n"; simply inserts a line break. This line is unnecessary, but will make our source code easier to read.
Once we understand the first couple of lines, the rest is pretty much self-explanatory.

So, ready to try it out? Upload everything to your site. The code works in such a way that everything should be in the same folder (to keep it simple). That means:

BG.png
quizbg.png
quiz.php
data1.xml

So, if your location is the folder ‘mcq’ on ‘website.com’, you type the address:

www.website.com/mcq/quiz.php?q=1

Did it work? Yes? Good. No? Go back and see where you went wrong. PHP is a fussy language and a missing semicolon can cause trouble. Don’t forget that you can download a working version from www.flashbynight.com/tutes/html5quiz/1/version2.zip.

Once it’s working, rightclick on the page and click ‘view source’. Scroll down and can you see how the browser reads the PHP code? It should read like this:

Questions[0]='Where is Paris?';
Options[0]=['France','Belgium','Norway'];
Questions[1]='Where is London?';
Options[1]=['England','China','Denmark'];
Questions[2]='Where is Rome?';
Options[2]=['Italy','Brazil','Canada'];

 

Done!

We’re all done!

There were so many things to learn in this tutorial! And now you can create an HTML5 quiz. Play around with it and do your own thing.

You have my full permission to use the code as you wish in your own projects, but please do not reproduce this tutorial. I have made this tutorial available on my site and Scribd.com and by extension, sites that access feeds from Scribd.com.

Want more tutorials? Try here: www.flashbynight.com/tutes

And come and try some of my games at www.flashbynight.com There are word games, puzzles and arcade games and more.

Thank you for using my tutorial and happy coding!

=====================================================================================

Completed Code for quiz.html

<!DOCTYPE HTML>

<html>
    <head>
        <style>
            body {
                      background-image:url('BG.png');
                        }
            #ccontainer{
                        width:550px;
                        margin: 0 auto;
                        margin-top:100px;
                         }
            #myCanvas {
                      //background:#FFFFFF;
            }

        </style>

        <script>
            window.onload = function(){

                      var canvas = document.getElementById("myCanvas");
                      var context = canvas.getContext("2d");
                      var quizbg = new Image();
                      var Question = new String;
                      var Option1 = new String;
                      var Option2 = new String;
                      var Option3 = new String;
                      var mx=0;
                      var my=0;
                      var CorrectAnswer = 0;
                      var qnumber = 0;
                      var rightanswers=0;
                      var wronganswers=0;
                      var QuizFinished = false;
                      var lock = false;
                      var textpos1=45;
                      var textpos2=145;
                      var textpos3=230;
                      var textpos4=325;
                      var Questions = ["Where is Paris?","Where is London?","Where is Rome?"];
                      var Options = [["France","Belgium","Norway"] , ["England","China","Denmark"] , ["Italy","Brazil","Canada"]];

        quizbg.onload = function(){
                        context.drawImage(quizbg, 0, 0);
                        SetQuestions();
        }//quizbg
        quizbg.src = "quizbg.png";

        SetQuestions = function(){
                      Question=Questions[qnumber];
                      CorrectAnswer=1+Math.floor(Math.random()*3);

if(CorrectAnswer==1){Option1=Options[qnumber][0];Option2=Options[qnumber][1];Option3=Options[qnumber][2];}                                                  if(CorrectAnswer==2){Option1=Options[qnumber][2];Option2=Options[qnumber][0];Option3=Options[qnumber][1];}
if(CorrectAnswer==3){Option1=Options[qnumber][1];Option2=Options[qnumber][2];Option3=Options[qnumber][0];}

                      context.textBaseline = "middle";
                      context.font = "24pt Calibri,Arial";
                      context.fillText(Question,20,textpos1);
                      context.font = "18pt Calibri,Arial";
                      context.fillText(Option1,20,textpos2);
                      context.fillText(Option2,20,textpos3);
                      context.fillText(Option3,20,textpos4);
      }//SetQuestions

      canvas.addEventListener('click',ProcessClick,false);

      function ProcessClick(ev) {
                      my=ev.y-canvas.offsetTop;
                      if(ev.y == undefined){
                                      my = ev.pageY - canvas.offsetTop;
                      }
                      if(lock){
                                      ResetQ();
                      }//if lock

                      else{
                                      if(my>110 && my<180){GetFeedback(1);}
                                      if(my>200 && my<270){GetFeedback(2);}
                                      if(my>290 && my<360){GetFeedback(3);}
                      }//!lock
}//ProcessClick

      GetFeedback = function(a){
                      if(a==CorrectAnswer){
                              context.drawImage(quizbg, 0,400,75,70,480,110+(90*(a-1)),75,70);
                              rightanswers++;
                                     
                        }
                        else{
                              context.drawImage(quizbg, 75,400,75,70,480,110+(90*(a-1)),75,70);
                              wronganswers++;
                        }
                        lock=true;
                        context.font = "14pt Calibri,Arial";
                        context.fillText("Click again to continue",20,380);
      }//get feedback

      ResetQ= function(){
                      lock=false;
                      context.clearRect(0,0,550,400);
                      qnumber++;
                      if(qnumber==Questions.length){EndQuiz();}
                      else{
                            context.drawImage(quizbg, 0, 0);
                            SetQuestions();}
                      }

      EndQuiz=function(){
                      canvas.removeEventListener('click',ProcessClick,false);
                      context.drawImage(quizbg, 0,0,550,90,0,0,550,400);
                      context.font = "20pt Calibri,Arial";
                      context.fillText("You have finished the quiz!",20,100);
                      context.font = "16pt Calibri,Arial";
                      context.fillText("Correct answers: "+String(rightanswers),20,200);
                      context.fillText("Wrong answers: "+String(wronganswers),20,240);
                      }
};//windowonload

</script>
</head>
 <body>
<div id="ccontainer">
<canvas id="myCanvas" width="550" height="400"></canvas>
</div>
</body>
</html>