Create an interactive HTML5 Canvas using event handlers.

You can use HTML5 Canvas as an alternative approach designing info graphics, branding graphics etc. Using the example in my previous blog post, I will add a clickable area on the canvas and use a JavaScript event handler to execute some logic.

This is the result of the previous example. I want to pop an alert Box when clicking inside the logo.


I need to create an object reflecting the coordinates I want my clickable zone to have. I’m also throwing in an id/name.

    var CustFigure = function (x, y, height, width, name ) {
    this.x = x;
    this.y = y;
    this.height = height;
    this.width = width;
    this.name = name;
    };

In this case I just create a global Array that I can pop the objects on to.  

    var custFigures = [];

At some point (I choose to include it in the function drawing the logo) we create the object with the desired coordinates and push it on to the array.

    var custFigure = new CustFigure(50, 50, 75+50, 75+50, " Hello Nerd!");
    custFigures.push(custFigure);

Now, for the final section; adding the logic to the canvas click event handler.  

   $('#xpCanvasWeb').click(function (e) {
    //Picking up the cursor coordinates
    var clickedX = e.pageX - this.offsetLeft;
    var clickedY = e.pageY - this.offsetTop;
    //You might have more than one clickable zone in your canvas. 
    //We run through the array and compare the coordinates.
    for (var i = 0; i < custFigures.length; i++) {

        if (clickedX > custFigures[i].x
            && clickedX < custFigures[i].width
            && clickedY > custFigures[i].y
            && clickedY < custFigures[i].height) {
            var name = custFigures[i].name;
            //When matching we fire of the alert box.
            alert("You clicked X=" + clickedX + " and Y=" + clickedY + name);
        }
    }
   });

The result should look something like the box below.



Comments

Popular posts from this blog

Designing and programming - Part 2

Filtering Dropdown choices in a Power Pages form using Dataverse Relations

Exploring the Power of Variables in Liquid and Power Pages