Canvas

HTML5 canvas cheatsheet

Our colleague, Colin Cieloha, American author and content marketer at Skilled.co recommended the HTML5 canvas cheatsheet developed by his company (and embedded below).

Colin Cieloha

Colin writes about everything that will draw his attention with a focus on the mobile and e-commerce space.  When he is not writing he is spending his time traveling the globe and snowboarding.  You can follow him on his Twitter at @ColinCieloha or on Linkedin. We asked Colin a number of questions about this resource. Details are below.

Become a Canvas Master with this HTML5 Cheat Sheet by Skilled.co

Skilled.co has released a new cheat sheet that enables new and experienced web developers alike to create original illustrations and animations. With the use of HTML5 advanced technology, coding enthusiasts of all experience levels are able to read and use this cheat sheet to create impressive designs. Canvas can also respond to all the usual JavaScript events, like clicking and keyboard commands and button clicks, so it’s even easier to use. Here we will explore the benefits of using the Canvas cheat sheet and how Canvas holds up against traditional Camel Case. It’s sure to save you time, effort, and headache.

Why is it important for web professionals to know/ use this cheat sheet?

It saves time! Instead of having to remember all the coding or search for individual codes, an HTML cheat sheet provides all of the most used codes in one easy place. There’s a lot to be said for having all of that extra effort minimized, the common codes are just a click of your bookmarks away. This is convenient for those freelance designers that are in a time crunch as this allows them to complete their work faster and reach deadlines.

Why should they be focused on canvas now?

Canvas technology is amazing because it’s super easy to use. For example, Canvas can draw colorful text to help your message pop on the screen – and you can even animate it! HTML <canvas> objects can move, too, whether it’s just a few bouncing balls or an intricate animation that tells a story. For designers interested in gaming software, the <canvas> element is a brilliant choice for building characters, worlds, and then setting it all into motion.

Canvas isn’t magic (close, but not magic). You’ll still need a basic understanding of HTML and JavaScript to make these codes work for you the way you want, but the <canvas> element is simple and easy to use. The HTML <canvas> element’s purpose is to create graphics, according to lines of script, but it’s only a container. The <canvas> element draws paths, boxes, circles, text, and helps you to create images. It also provides the user with graphs and charts to order their graphic data designs. To draw graphics, Canvas uses a JavaScript context object, which makes it easy and fast to create graphics in your design.

The <canvas> element runs into some trouble with older browsers, however, and may not be supported. Canvas is, however, supported in all recent versions of all major browsers, so as long as your browser is updated, Canvas should work just fine. Canvas’s default size is three hundred pixels by one hundred and fifty pixels, width and height respectively, but is customizable. You can adjust the size of the canvas by using the HTML height and width property in the program.

With Canvas, function names are short and easy to recognize, unlike functions written in CamelCase. Identifiers in CamelCase often require lowercase where it would be more convenient to use all caps. For example, acronyms. It’s much easier to identify a function, if acronyms like HTML or SQL are written in full capitalization, but CamelCase sometimes negates this convenience.

This causes a serious headache for designers when two acronyms need to be side by side in a line of script: “parse DBM XML” would become “parseDBMXML” or when the function starts with an acronym, like “SQL server” (which the designer would be forced to convert to “sQLServer”). Even if a programmer considers acronyms lower case words and writes “oldHtmlFile”, “parseDbmXml” or “sqlServer”, it causes a mess because it makes it difficult to discern if it an acronym or not. Best case scenario, the designer wastes time.  The worst case scenario, they make a mistake and now must comb through complicated lines of script to amend the problem.

Conclusion

Hopefully this sheds light on the massive benefits of the Canvas cheat sheet. Using this cheat sheet will save you time and help you to become a more efficient programmer, web designer, or even help you gain more solid experience as a beginner in this field. I encourage you to go check out Skilled.co‘s Canvas cheat sheet below and begin to create using their helpful, easy to read codes. Have fun creating and I hope this saves you more time!

The post HTML5 canvas cheatsheet appeared first on Web Professionals.

View full post on Web Professional Minute

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Quick one: using download attribute on links to save Canvas as PNG

One of the things I always liked about Firefox is that you can right-click any canvas and select “save image as”. Chrome and others don’t do that (well, Chrome doesn’t). Instead you need to get the image data, create a url and open a new tab or something in that order.

One very simple way to allow people to save a canvas as an image (and name it differently – which would have to be done by hand in the case of right-clicking on Firefox) is to use the download attribute of a link.

You can see this in action in this JSFiddle. Simply paint something and click the “download image” link.

The relevant code is short and sweet (canvas is the reference of the canvas element):

var link = document.createElement('a');
link.innerHTML = 'download image';
link.addEventListener('click', function(ev) {
    link.href = canvas.toDataURL();
    link.download = "mypainting.png";
}, false);
document.body.appendChild(link);

View full post on Christian Heilmann

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Introducing the Canvas Debugger in Firefox Developer Tools

The Canvas Debugger is a new tool we’ll be demoing at the Game Developers Conference in San Francisco. It’s a tool for debugging animation frames rendered on a Canvas element. Whether you’re creating a visualization, animation or debugging a game, this tool will help you understand and optimize your animation loop. It will let you debug either a WebGL or 2D Canvas context.

Canvas Debugger Screenshot

You can debug an animation using a traditional debugger, like our own JavaScript Debugger in Firefox’ Developer Tools. However, this can be difficult as it becomes a manual search for all of the various canvas methods you may wish to step through. The Canvas Debugger is designed to let you view the rendering calls from the perspective of the animation loop itself, giving you a much better overview of what’s happening.

How it works

The Canvas Debugger works by creating a snapshot of everything that happens while rendering a frame. It records all canvas context method calls. Each frame snapshot contains a list of context method calls and the associated JavaScript stack. By inspecting this stack, a developer can trace the call back to the higher level function invoked by the app or engine that caused something to be drawn.

Certain types of Canvas context functions are highlighted to make them easier to spot in the snapshot. Quickly scrolling through the list, a developer can easily spot draw calls or redundant operations.

Canvas Debugger Call Highlighting Detail

Each draw call has an associated screenshot arranged in a timeline at the bottom of the screen as a “film-strip” view. You can “scrub” through this film-strip using a slider to quickly locate a draw call associated with a particular bit of rendering. You can also click a thumbnail to be taken directly to the associated draw call in the animation frame snapshot.

Canvas Debugger Timeline Picture

The thumbnail film-strip gives you get a quick overview of the drawing process. You can easily see how the scene is composed to get the final rendering.

Stepping Around

You might notice a familiar row of buttons in the attached screenshot. They’ve been borrowed from the JavaScript Debugger and provide the developer a means to navigate through the animation snapshot. These buttons may change their icons at final release, but for now, we’ll describe them as they currently look.

Canvas Debugger Buttons image

  • “Resume” – Jump to the next draw call.
  • “Step Over” – Goes over the current context call.
  • “Step Out” – Jumps out of the animation frame (typically to the next requestAnimationFrame call).
  • “Step In” – Goes to the next non-context call in the JavaScript debugger

Jumping to the JavaScript debugger by “stepping in” on a snapshot function call, or via a function’s stack, allows you to add a breakpoint and instantly pause if the animation is still running. Much convenience!

Future Work

We’re not done. We have some enhancements to make this tool even better.

  • Add the ability to inspect the context’s state at each method call. Highlight the differences in state between calls.
  • Measure Time spent in each draw call. This will readily show expensive canvas operations.
  • Make it easier to know which programs and shaders are currently in use at each draw call, allowing you to jump to the Shader Editor and tinkering with shaders in real time. Better linkage to the Shader Editor in general.
  • Inspecting Hit Regions by either drawing individual regions separately, colored differently by id, or showing the hit region id of a pixel when hovering over the preview panel using the mouse.

And we’re just getting started. The Canvas Debugger should be landing in Firefox Nightly any day now. Watch this space for news of its landing and more updates.

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Image masking with HTML5 Canvas

I just added a small demo to my GitHub showing how you can do image masking by using the canvas element.

masks

All you need to do is add the canvasmask.js script and add a class of mask to each image you want to mask. You also need to provide a PNG file as the mask using the data-mask attribute. For example:

<img src="red-panda.jpg" 
     alt="Red panda" 
     class="mask" 
     data-mask="centerblur.png">

This will take the centerblur.png file and apply it as a mask to red-panda.jpg – in effect taking the alpha of each pixel and change the alpha of the original pixel to that.

You can see it in action here and get the code on GitHub.

Under the hood, all I do is loop through all the pixels of the images (after copying them to two canvas elements) and apply the alpha values (every 4th value in the pixeldata array) of the PNG to the image. Simple, really 🙂

As mentioned by Jake Archibald on Twitter there is no need to loop over the pixels of the images, all you need is to copy the mask first, then change the canvas compositing to source-atop and add the image. Done. The script does that now, and thus is much faster.

View full post on Christian Heilmann

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Irregular shape rollovers with Canvas and PNG

Creating rollovers is easy. Much easier than it was in the past with the infamous MM_mouseover at least. It gets tricky though when you want to have the rollover only happen on a certain shape and not only in a rectangular area.

There are many solutions to this, like SVG masking or adding lots of rectangular overlays that make up the desired shape, but I wanted to have a simple solution. You can see the solution working here in this GIF:

rollover triggered on irregular shapes

What I am doing here is adding PNGs (courtesy Game Icons) with transparency to the HTML and give them a class of rollover:

<img 
     src="bottle.png" 
     alt="bottle vapours" 
     class="rollover">
<img src="burning-embers.png" 
     alt="burning embers" 
     class="rollover">

The transparent part of the PNG will be what should not trigger the rollover, and all other pixels should.

The JavaScript is pretty simple and based on the principles used in the letterpaint game I just explained on Mozilla Hacks.

  • Loop over all images with the class “rollover”
  • Add a mouseover, mouseout and mousemove event to each
  • On mouseover, take the image and copy it to an invisible Canvas element
  • On mousemove, find out the x and y position of the mouse cursor and read the colour of the pixel at this position from the canvas
  • If the pixel has an opacity of 0, it is transparent, which means remove the “over” class from the image.
  • If the pixel is not opaque, add the class “over” to the image.

You can try this out here.

The source code is on GitHub.

This seems to be a very simple way to have irregular shaped rollovers. You could enhance the hover() function to also react differently depending of which part of the shape you are on. You can also add touch handlers easily. The only caveat is that the images and the JavaScript need to be on the same domain or the canvas is not allowed to access the pixels of the image.

View full post on Christian Heilmann

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Building a simple paint game with HTML5 Canvas and Vanilla JavaScript

When the talk is about HTML5 Canvas you mostly hear about libraries to make it work for legacy browsers, performance tricks like off-screen Canvas and ways to draw and animate sprites and tiles. This is only one part of Canvas, though. On the lowest level, Canvas is a way to manipulate pixels of a portion of the screen. Either via a painting API or by directly manipulating the pixel array (which by the way is a typed array and thus performs admirably).

Using this knowledge, I thought it’d be fun to create a small game I saw in an ad for a tablet: a simple game for kids to paint letters. The result is a demo for FirefoxOS called Letterpaint which will show up soon on the Marketplace. The code is on GitHub.

letterpaint

The fun thing about building Letterpaint was that I took a lot of shortcuts. Painting on a canvas is easy (and gets much easier using Jacob Seidelin’s Canvas cheatsheet), but on the first glance making sure that users stay in a certain shape is tricky. So is finding out how much of the letter has been filled in. However, by going back to seeing a Canvas as a collection of pixels, I found a simple way to make this work:

  • When I paint the letter, I read out the amount of pixels that have the colour of the letter
  • When you click the mouse button or touch the screen I test the colour of the pixel at the current mouse/finger position
  • When the pixel is not transparent, you are inside the letter as the main Canvas by default is transparent
  • When you release the mouse or stop touching the screen I compare the amount of pixels of the paint colour with the ones of the letter.

Simple, isn’t it? And it is all possible with two re-usable functions:

/*
  getpixelcolour(x, y)
  returns the rgba value of the pixel at position x and y
*/
function getpixelcolour(x, y) {
  var pixels = cx.getImageData(0, 0, c.width, c.height);
  var index = ((y * (pixels.width * 4)) + (x * 4));
  return {
    r: pixels.data[index],
    g: pixels.data[index + 1],
    b: pixels.data[index + 2],
    a: pixels.data[index + 3]
  };
}
 
/*
  getpixelamount(r, g, b)
  returns the amount of pixels in the canvas of the colour 
  provided
*/
function getpixelamount(r, g, b) {
  var pixels = cx.getImageData(0, 0, c.width, c.height);
  var all = pixels.data.length;
  var amount = 0;
  for (i = 0; i < all; i += 4) {
    if (pixels.data[i] === r &&
        pixels.data[i + 1] === g &&
        pixels.data[i + 2] === b) {
      amount++;
    }
  }
  return amount;
}

Add some painting functions to that and you have the game done. You can see a step by step guide of this online (and pull the code from GitHub) and there is a screencast describing the tricks and decisions on YouTube.

The main thing to remember here is that it is very tempting to reach for libraries and tools to get things done quickly, but that it could mean that you think too complex. Browsers have very powerful tools built in for us, and in many cases it means you just need to be up-to-date and fearless in trying something “new” that comes out-of-the-box.

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Firefox Development Highlights – Per Window Private Browsing & Canvas’ globalCompositeOperation new values

On a regular basis, we like to highlight the latest features in Firefox for developers, as part of our Bleeding Edge series, and most examples only work in Firefox Nightly (and could be subject to change).

Per Window Private Browsing

Private browsing is very useful for web developers. A new private session doesn’t include existing persistent data (cookies and HTML5 storage). It’s convenient if we want to test a website that stores data (login and persistent informations) without cleaning every time these cached data, or if we want to login to a service with 2 different users.

Until now, when entering Private Browsing in Firefox, it was closing the existing session to start a new one. Now, Firefox will keep the current session and open a new private window. You can test it in Firefox Nightly (to be Firefox 20). There’s still some frontend work to do, but the feature works.

Canvas’ globalCompositeOperation new values

The ‘globalCompositeOperation’ canvas property lets you define how you want canvas to draw images over an existing image. By default, when canvas draws an image over existing pixels, the new image is just replacing the pixels. But there are other ways to mix pixels. For example, if you set ctx.globalCompositeOperation = "lighter", pixel color values are added, and it creates a different visual effect.

There are several effects available, and more on them can be found in globalCompositeOperation on MDN.

Rik Cabanier from Adobe has extended the Canvas specification to include more effects. He has also implemented these new effects in Firefox Nightly. These new effects are called “blend modes”. These are more advanced ways of mixing colors.

Please take a look at the list of these new blending modes.

And here’s an example of how to use them:

blend modes

If you don’t use Firefox Nightly, here is a (long) screenshot:

image

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)