Having fun with HTML5 – Canvas, part 3

You can become a serverless blackbelt. Enrol to my 4-week online workshop Production-Ready Serverless and gain hands-on experience building something from scratch using serverless technologies. At the end of the workshop, you should have a broader view of the challenges you will face as your serverless architecture matures and expands. You should also have a firm grasp on when serverless is a good fit for your system as well as common pitfalls you need to avoid. Sign up now and get 15% discount with the code yanprs15!

Following on from part 2 where I wrote a simple page with a canvas area where you can scribble, I thought I’d add a couple of new features:

  • ability to show the image as PNG image so user can save it
  • change the line cap
  • change the line join
  • change the shadow settings (colour, offset, blur)

Show PNG

The <canvas> element defines a rather useful toDataURL() method:

“The toDataURL() method must, when called with no arguments, return a data: URL containing a representation of the image as a PNG file.”

To get the data in PNG format and get the browser to render it for the user:

// display the image
$("#btnShowPng").click(function () {
    window.location = element.toDataURL("image/png");
});

Couldn’t be simpler, right?!

Changing the lineCap property

The 2D context defines a lineCap property which you can set to butt, round or square, it determines the ending style of the line (default is butt):

image

So here’s a simple set of radio buttons:

<article>
    Line cap:
    <input type="radio" name="linecap" value="butt" checked="checked"/>Butt
    <input type="radio" name="linecap" value="round"/>Round
    <input type="radio" name="linecap" value="square"/>Square
</article>

image

and an event handler for their change events:

// change the linecap when the "linecap" radio button changes
$("input[name=linecap]:radio").change(function (event) {
    context.lineCap = event.target.value;
});

Changing the lineJoin property

In addition to the lineCap property, the 2D context also defines a lineJoin property which can be set to miter, round or bevel, it determines how the corners look (default is miter):

image

Here’s the set of radio buttons:

<article>
    Line join:
    <input type="radio" name="linejoin" value="miter" checked="checked"/>Miter
    <input type="radio" name="linejoin" value="round"/>Round
    <input type="radio" name="linejoin" value="bevel"/>Bevel
</article>

image

and its corresponding event handler:

// change the linecap when the "linejoin" radio button changes
$("input[name=linejoin]:radio").change(function (event) {
    context.lineJoin = event.target.value;
});

Changing the Shadow properties

The 2D context has a couple of shadow related properties:

  • shadowColor
  • shadowOffsetX
  • shadowOffsetY
  • shadowBlur

The shadowColor property can take in a colour using the rgba function (default value is “rgba(0, 0, 0, 0)”, i.e. a fully transparent black), whilst the other properties require a numeric value greater than or equal to 0.

Here’s the HTML marker for configuring the shadow properties:

<article>
    <section id="shadowColorSection">
        Shadow Colour:
        R
        <input type="text" id="txtColourR" value="0" class="narrow" />
        G
        <input type="text" id="txtColourG" value="0" class="narrow" />
        B
        <input type="text" id="txtColourB" value="0" class="narrow" />
        A
        <input type="text" id="txtColourA" value="0" class="narrow" />
    </section>

    <section>
        Shadow Offset:
        X
        <input type="text" id="txtOffsetX" value="0" class="narrow" />
        Y
        <input type="text" id="txtOffsetY" value="0" class="narrow" />
    </section>

    <section>
        Shadow Blur:
        <input type="text" id="txtBlur" value="0" class="narrow" />
    </section>
</article>

image

and the javascript to go along with them:

$("#shadowColorSection > input:text").change(function (event) {
    setShadowColour(context);
});

$("#txtOffsetX").change(function (event) {
    context.shadowOffsetX = event.target.value;
});

$("#txtOffsetY").change(function (event) {
    context.shadowOffsetY = event.target.value;
});

$("#txtBlur").change(function (event) {
    context.shadowBlur = event.target.value;
});

…

// set the shadow colour from the RBGA text boxes
function setShadowColour(context) {
    var r = $("#txtColourR").val(),
        g = $("#txtColourG").val(),
        b = $("#txtColourB").val(),
        a = $("#txtColourA").val();

    context.shadowColor = "rgba(" + r + "," + g + "," + b + "," + a + ")";
}

Updating the Clear button handler

Now that we can modify a few more of 2D context’s properties, it’d be nice if the changes are remembered after we clear the canvas, so the Clear button’s event handler needs to be modified too to keep track of the current values and reapplying them:

// clear the content of the canvas by resizing the element
$("#btnClear").click(function () {
    // remember the current line width
    var currentWidth = context.lineWidth,
        currentLineCap = context.lineCap,
        currentLineJoin = context.lineJoin;
    var currentShadowColour = context.shadowColor,
        currentShadowOffsetX = context.shadowOffsetX,
        currentShadowOffsetY = context.shadowOffsetY,
        currentShadowBlur = context.shadowBlur;

    // set the element's width to erase canvas content
    element.width = element.width;

    context.lineWidth = currentWidth;
    context.lineCap = currentLineCap;
    context.lineJoin = currentLineJoin;

    context.shadowColor = currentShadowColour;
    context.shadowOffsetX = currentShadowOffsetX;
    context.shadowOffsetY = currentShadowOffsetY;
    context.shadowBlur = currentShadowBlur;
});

Demo

The demo can be found here.

Related posts:

Having fun with HTML5 – Canvas, part 1

Having fun with HTML5 – Canvas, part 2

Having fun with HTML5 – Canvas, part 4

Having fun with HTML5 – Canvas, part 5

Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.
Subscribe to my newsletter


Hi, I’m Yan. I’m an AWS Serverless Hero and I help companies go faster for less by adopting serverless technologies successfully.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Hire me.


Skill up your serverless game with this hands-on workshop.

My 4-week Production-Ready Serverless online workshop is back!

This course takes you through building a production-ready serverless web application from testing, deployment, security, all the way through to observability. The motivation for this course is to give you hands-on experience building something with serverless technologies while giving you a broader view of the challenges you will face as the architecture matures and expands.

We will start at the basics and give you a firm introduction to Lambda and all the relevant concepts and service features (including the latest announcements in 2020). And then gradually ramping up and cover a wide array of topics such as API security, testing strategies, CI/CD, secret management, and operational best practices for monitoring and troubleshooting.

If you enrol now you can also get 15% OFF with the promo code “yanprs15”.

Enrol now and SAVE 15%.


Check out my new podcast Real-World Serverless where I talk with engineers who are building amazing things with serverless technologies and discuss the real-world use cases and challenges they face. If you’re interested in what people are actually doing with serverless and what it’s really like to be working with serverless day-to-day, then this is the podcast for you.


Check out my new course, Learn you some Lambda best practice for great good! In this course, you will learn best practices for working with AWS Lambda in terms of performance, cost, security, scalability, resilience and observability. We will also cover latest features from re:Invent 2019 such as Provisioned Concurrency and Lambda Destinations. Enrol now and start learning!


Check out my video course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. There is something for everyone from beginners to more advanced users looking for design patterns and best practices. Enrol now and start learning!