Mastering the HTML5 Canvas: Part 1
Join the DZone community and get the full member experience.
Join For Free
this post comes from
graham murray
at the infragistics blog.
this is the first in a series of blog posts about mastering the html5 canvas element. we’ll be focusing first on animation as it is one of the best ways to leverage the canvas to bring new interaction types and visualizations to your web applications. here’s a preview of what we are building for part one.
canvas overview
the html5 canvas element provides an immediate mode 2-d rendering api that we can use in our web applications. it depends on no browser plugins and it only requires a modern enough browser that supports the html5 canvas component. even if you're trying to support older versions of internet explorer (8 and below), there are some polyfills that can be used to attempt to provide support for them (flashcanvas, excanvas, etc.).
because canvas is an immediate-mode rendering engine, rather than building an object graph that represents all the objects that are visible (as you would in a retained mode system like silverlight or wpf), we will talk to the rendering context of the canvas and, for each frame, we will tell it which visual primitives to render at which locations.
hello circle
to begin with, let's render a circle on the screen.
we will assume that jquery has been referenced for this web application to assist us in manipulating the required dom elements succinctly. but jquery is certainly not required in order to interact with the canvas. first, we will start with the dom. we need to add a canvas element somewhere in our dom hierarchy where we want to display the canvas content. in this case, it's the only element in my page body.
<canvas id="canvas"></canvas>
i’ve provided an id so that we can easily find this element later when we want to render its content.
now it's time to render the circle into the canvas. we need to start by acquiring the 2-d rendering context from the canvas. the rendering context is what surfaces to us the api that we need in order to render primitives into the canvas.
$(function () { var canv, context; $("#canvas").attr("width", "500px").attr("height", "500px"); canv = $("#canvas")[0]; context = canv.getcontext("2d");
here we are using jquery to locate the canvas by id, then setting its width and height. something that may confuse you initially is that there are really two widths and heights that are relevant to the canvas. the canvas element has attributes for width and height that represent the size of the bitmap that is used for rendering content within the canvas. meanwhile, you can also set a css width and height on the canvas. these represent the size to which the bitmap generated by the canvas is scaled when displayed on the page. so, for example, if you created a 50px by 50px canvas and scaled it to 500px by 500px, it would look very blocky since you would be stretching a 50px square to fill a 500px square area. most of the time, you will probably want the css size to be the same as the attribute size of the canvas.
next, we extract a reference to the canvas dom element from jquery and call getcontext(“2d”) to get the rendering context. why getcontext(“2d”)? this is because the html5 canvas also plays an integral role in webgl beyond its 2-d api, but for now, we are talking about 2-d.
then we render the actual circle. here i’m defining a function called "draw" that will render the circle and then call it to do the actual rendering. why did i split this up? this will become apparent when we add animation to the mix.
function draw() { context.fillstyle = "rgb(255,0,0)"; context.beginpath(); context.arc(150, 150, 120, 0, 2 * math.pi, false); context.fill(); } draw();
here we are:
- setting the fill style of the canvas to red; you can use most syntax that a css color property will accept here.
- telling the context to begin a new path
- drawing an arc with a center at 150px and 150px with a radius of 120, sweeping from zero to 360 degrees, in a clockwise direction (note that the api actually wants radians, not degrees.)
- telling the context to fill the path that we have defined, thus filling the circle
and here is the result .
hello animation
now, let's animate our circle in some way.
first, here’s the modified logic from our previous version:
var canv, context, lasttime, duration, progress, forward = true; $("#canvas").attr("width", "500px").attr("height", "500px"); canv = $("#canvas")[0]; context = canv.getcontext("2d"); lasttime = new date().gettime(); duration = 1000; progress = 0; function draw() { var elapsed, time, b; time = new date().gettime(); elapsed = time - lasttime; lasttime = time; if (forward) { progress += elapsed / duration; } else { progress -= elapsed / duration; } if (progress > 1.0) { progress = 1.0; forward = false; } if (progress < 0) { progress = 0; forward = true; } b = 255.0 * progress; context.fillstyle = "rgb(255," + math.round(b.tostring()) + ",0)"; context.beginpath(); context.arc(150, 150, 120, 0, 2 * math.pi, false); context.fill(); } window.setinterval(draw, 1000 / 60.0);
so what are the differences above?
first, we are using window.setinterval to call our draw method repeatedly. we are attempting to do this 60 times a second (1000 milliseconds / 60.0).
window.setinterval(draw, 1000 / 60.0);
next, for each time we draw, we determine how much time elapsed since the last frame that was drawn and we update our progress toward the completion of the animation. when the progress reaches completion, we reverse the direction and decrease it back down to zero. then, when we hit zero, we turn around and progress toward one again. this way, the animation just loops backward and forward continually.
time = new date().gettime(); elapsed = time - lasttime; lasttime = time; if (forward) { progress += elapsed / duration; } else { progress -= elapsed / duration; } if (progress > 1.0) { progress = 1.0; forward = false; } if (progress < 0) { progress = 0; forward = true; }
next, the progress is used to drive the color we are using to render the ellipse.
b = 255.0 * progress; context.fillstyle = "rgb(255," + math.round(b.tostring()) + ",0)";
and so we have an ellipse that animates in color.
improving our animation
we can make a small adjustment to the above logic in order to improve the way that the animation is performed. there are two assumptions that the above logic makes that are not necessarily true: it assumes both that the machine running the logic will be fast enough to provide a 60 frames per second (fps) animation, and that the draw method will be called with reliable enough timing to create a smooth animated effect. the machine may be too slow to perform the animation update the required number of times per second, and setinterval is not guaranteed to be called reliably at all, especially if lots of logic is hammering the javascript event queue. some modern browsers support an api that lets us do better than this when performing animation. we can essentially request that the browser notify us when an animation frame is ready, so that we can respond by rendering some content. this provides more reliable and smooth animation, and should let us avoid trying to animate more frames than the system is able to handle. here is the modified version of the logic that will use a polyfill in order to use the requestanimationframe api, if present, and otherwise fall back on our previous method for animating if we are on a browser that does not support requestanimationframe.
function ensurequeueframe() { if (!window.queueframe) { if (window.requestanimationframe) { window.queueframe = window.requestanimationframe; } else if (window.webkitrequestanimationframe) { window.queueframe = window.webkitrequestanimationframe; } else if (window.mozrequestanimationframe) { window.queueframe = window.mozrequestanimationframe; } else { window.queueframe = function (callback) { window.settimeout(1000.0 / 60.0, callback); }; } } } $(function () { var canv, context, lasttime, duration, progress, forward = true; ensurequeueframe(); $("#canvas").attr("width", "500px").attr("height", "500px"); canv = $("#canvas")[0]; context = canv.getcontext("2d"); lasttime = new date().gettime(); duration = 1000; progress = 0; function draw() { var ellapsed, time, b; queueframe(draw); time = new date().gettime(); ellapsed = time - lasttime; lasttime = time; if (forward) { progress += ellapsed / duration; } else { progress -= ellapsed / duration; } if (progress > 1.0) { progress = 1.0; forward = false; } if (progress < 0) { progress = 0; forward = true; } b = 255.0 * progress; context.fillstyle = "rgb(255," + math.round(b.tostring()) + ",0)"; context.beginpath(); context.arc(150, 150, 120, 0, 2 * math.pi, false); context.fill(); } queueframe(draw); });
next time
next time, we will take on something much more ambitious : we will build an eye-catching animation that reacts to the mouse movement over the canvas. we will also simulate some 3-d effects using 2-d rendering but with 3-d matrix transformations.
Published at DZone with permission of Josh Anderson, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Tech Hiring: Trends, Predictions, and Strategies for Success
-
Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
-
AI and Cybersecurity Protecting Against Emerging Threats
-
Knowing and Valuing Apache Kafka’s ISR (In-Sync Replicas)
Comments