What is the real benefit of using canvas for games? - javascript

I'm currently reading up on the canvas, but I'm finding it hard to find practical benefits of using canvas, when a lot can be done using simple css overlays/JavaScript (+ jquery lib).
This is probably because I don't know the FULL practicalities of using canvas.
Looking at this game:
http://www.pirateslovedaisies.com/
Could someone help explain how and why canvas is being used as opposed to just css?

This is a 4k js/canvas demo I wrote to experiment with the 2d context (here is a video if your browser doesn't work). I tested it only on chrome, opera, firefox, safari and nexus one browser.
Note that no external resources are loaded (i.e. the texture and the raytraced envmap are built dynamically), so this is just a single self-contained 4096 bytes HTML file.
You can do something like that with DIVs?
But indeed I agree that the game you linked IMO could be done also with DIVs; apparently there are no transformations - not even in the falling daisy loading scene - and the action areas for the pirates are just circles. Not sure but could be that even shooting only happens at fixed angles.
Canvas could have been used instead for:
Drawing general sloped lines and polygons (the map could be created dinamically from a compact description or could have been generated randomly). Shooting could be done at any angle...
Procedural image creation (e.g. textures or special pixel effects)
Gradients, texture mapping
General 2d matrix transforms
Of course a game using an image+DIVs approach is probably way easier to make (a lot of photoshop and simple xy animation).

Creating tons of HTML elements is extremely slow and memory-hungry. The canvas object is made for graphics operations and thus optimized for it. Besides that.. how would you draw a curve with plain HTML/CSS? ;)

Using <canvas> you have a per-pixel control of what's shown on the screen. You don't have to deal with specific browser CSS or DOM compatibility.
Also, that's actually a pretty similar programming model to 2D non-browser games, like those created using SDL o DirectDraw.

Here's a game I wrote in a few hours using Canvas; note that the scaling of the tiles, the anti-aliasing of the lines, is perfect. This would not be the case with image tiles that were being resized by the browser.
Click the tiles to rotate them in an attempt to make all connections. Click the row of buttons at the top for a new board of a different size; click the row of buttons below that for a new board with different numbers of connections.
The game concept is not mine, only the implementation.

Related

How can I increase map rendering performance in HTML Canvas?

We are developing a web-based game. The map has a fixed size and is procedually generated.
At the moment, all these polygons are stored in one array and checked whether they should be drawn or not. This requires a lot of performance. Which is the best rendering / buffering solution for big maps?
What I've tried:
Quadtrees. Problem: Performance still not as great because there are so many polygons.
Drawing sections of the map to offscreen-canvases. A test run: http://norizon.ch/repo/buffered-map-rendering/ Problem: The browser crashes when trying to buffer that much data and such big images (maybe 2000x2000) still seem to perform badly on a canvas.
(posting comments as an answer for convenience)
One idea could be, when the user is translating the map, to re-use the part that will still be in view, and to draw only the stripe(s) that are no longer corrects.
I believe (do you confirm ?) that the most costly operation is the drawing, not to find which polygon to draw.
If so, you should use your QuadTree to find the polygons that are within the strips. Notice that, given Javascript's overhead, a simple 2D bucket that contains the polygons that are within a given (x,y) tile might be faster to use (if the cost of the quadtree is too high).
Now i have a doubt about the precise way you should do that, i'm afraid you'll have to experiment / benchmark, and maybe choose a prefered browser.
Problems :
• Copying a canvas on itself can be very slow depending on devices/Browsers. (might require to do 2 copy, in fact)
• Using an offscreen canvas can be very slow depending on devices/Browsers. (might not use hardware acceleration when off-screen).
If you are drawing things on top of the map, you can either use a secondary canvas on top of the map canvas, or you'll be forced to use an off-screen canvas that you'll copy on each frame.
I have tried a lot of things and this solution turned out to be the best for us.
Because our map has a fixed size, it is calculated server-side.
One big image atlas with all the required tiles will be loaded at the beginning of the game. For each image on the atlas, a seperate canvas is created. The client loads the whole map data into one two-dimensional array. The values determine, which tile has to be loaded. Maybe it would be even better if the map was drawn on a seperate canvas, so that only the stripes have to be painted. But the performance is really good, so we won't change that.
Three conclusions:
Images are fast. GetImageData is not!
JavaScript has not yet great support for multi threading, so we don't calculate the map client-side in game-time.
Quadtrees are fast. Arrays are faster.

Can I do a 1000% zoom with JavaScript vector art?

I'm planning to commission a developer to help me create a simple mathematical art piece. I'm wondering if the following can be accomplished with JavaScript vector art, and if not, what approach you would recommend.
The image will start off with some intersecting lines forming a shape. This is essentially an image zoomed in 1000% or more, and the user can scroll to zoom out until the full image fits the width of the screen.
Naturally, an actual image of this size would be huge, so I'm thinking it would be better to draw it programmatically, which might also enable the line thickness to scale up a bit as you zoom out, so that they're not nearly invisible when zoomed all the way out. The image can not look pixellated when zoomed all the way in, but achieving this with some “trickery” like swapping out images is also ok.
Example:
Basically the reverse of zoom.it but at a significantly larger scale.
http://zoom.it/
Some libraries I've looked at are:
paper.js
fabric.js
leaflet.js
raphael.js
How can an extreme zoomout like this be accomplished?
You are definitely on the right track. I think what you want is very possible on the web using HTML5. You are correct in that the easiest/best performing implementation of this would be using vector graphics. You can use image tiles, however the preprocessing and bandwidth requirements for tiling get large very quickly.
Here are some of my thoughts from working with some of the libraries you listed:
Leaflet.js - Leaflet supports both drawing SVG elements as well as image tiling (if you wanted to go that approach). Leaflet is also "mobile first" in that it supports things such as pinch zooming and double tap to zoom out of the box. Scroll zooming is also supported out of the box. Getting something up and going with Leaflet is simple. As far as I know Leaflet is writing SVG to the DOM; which is something to keep in mind.
Raphael - Raphael is capable of what you want, however you may need to implement zooming aspects yourself. This is definitely possible to do and shouldn't be too difficult, but something to keep in mind. Raphael will write SVG elements to the DOM; which can get a bit unruly if you have many many SVG elements. However, you may be able to optimize this and create/destroy elements as you are zooming.
Paper and Fabric - These both appear to render SVG to Canvas (different than writing SVG to the DOM). These both look really powerful, and seem to have good APIs for zooming. You would likely still need to hook up scroll/touch gestures to get zooming to work the way you want. These both should perform very well as they are using lower level APIs which should bypass many issues you might have with doing this in the DOM.

Spinning wheel or 360 degree rotation wheel

I am looking for some jquery plugin or any code examples for multiple spinning wheels or 360 degree rotation wheels. Attached is the demo image for which, I am looking for the solution, where all the wheel can be rotate and This is basically develop birthdate selection somewhat like desktop and mobile application...But I need for my web application. I am using PHP & Apache web server.
Thanks in advance for any idea or sameple code or similer solution to moving forward
-Himanshu
I don't know of any ready made solutions, but I can point you in two directions you can go:
You can make an image for each of the 3 different wheels with the correct sizes and next use css3 transformations to rotate the specific wheels with javascript ( https://developer.mozilla.org/en/CSS/transform#rotate )
The other option is to look into the html5 canvas tag and draw the wheels onto it by hand. Here is a tutorial which covers making a roulette game on a canvas tag, which is quite different from your requirements, but does describe the necessary techniques. http://www.switchonthecode.com/tutorials/creating-a-roulette-wheel-using-html5-canvas
Yes HTML5 canvas rotate() is the way to go with this. My site http://www.dougtesting.net has a winning wheel that uses canvas rotation, but only for one wheel image. The code is fully commented so you may find it a useful starting point.
For your project you would probably need multiple images that are rendered to the canvas and rotated to the desired angles. Also you will probably need to look in to a mouseDown, mouseMove, and mouseUp code to allow the user to drag the wheels to the desired locations, with the code being able to tell you the values pointed at (something the code in my winning wheel can also do).
I am not aware of a jQuery plugin that does exactly what you ask. In terms of browser compatibility, I recommend you to take a look at the excellent RaphaelJS JavaScript library. It allows you to draw and rotate a wheel using vector graphics. Best of all, this library is IE6+ compatible and works in most if not all modern webbrowsers, including tablets and mobile phones.
To ease the creation of the necessary vector graphics, you can draw the wheel in a vector image editor of your choice (e.g. Illustrator, Inkscape, etc..) and save the vector image as SVG file. A very convenient online companion tool called ReadySetRaphael takes an SVG file as input and produces the necessary JavaScript to draw the graphics automatically.
If you have the path of the vector graphic as an object in JavaScript, it is easy to rotate it with the Element.rotate() method.
Although I am not sure if a plugin exists for this purpose;In my current project we have made a context menu using the canvas api which is not that different from your requirement, if not a bit more complex. Therefore, I highly recommend using the HTML5 Canvas api to do this, if you are not restricted from it. You can use a few ideas from the interactive flower tutorial.
http://www.html5canvastutorials.com/labs/html5-canvas-interactive-flower/
This should help too if you're interested in bringing jQuery into play.
http://www.elated.com/res/File/articles/development/javascript/snazzy-animated-pie-chart-html5-jquery/

Combine Vector advantages with Bitmap in an HTML canvas element - how?

What I am trying to do is create a game that has an extreme amount of zoom-ability on a canvas element. I would like to make use of the advantage that vector graphics have insofar as being able to be programmatically created at runtime, with the high performance of bitmap images.
What I would like to do is programmatically create the first-frame image of a game "sprite"... this would be a vector image. After the first frame though, I do not want to keep wasting CPU cycles on drawing the image though.. i would like to cache it as a bitmap/high performance image for that zoom level.
Following this, if the user zooms in by >20%, I then redraw the image with a higher level of detail vector image. As above, this vector image would then be cached and optimized.
As you can see here, this would be a pretty basic space ship.. I would first render it programmatically as a vector and then.. raster it I guess? Goal is to avoid wasting CPU.
If the user zooms in...
A new vector image of the same shape would be drawn, albeit with a much higher level of detail. This is basically a Level Of Detail system. In this case as well, after the initial programmatic draw, I would "raster" the image for maximum performance.
Does anyone have ideas on what tools I would need to make this a reality inside of a HTML canvas? (The rest of the game will be running inside of the canvas element..)
Thank you very much for your thoughts.
**Edit: I wanted to add... perhaps the route of rendering an image via SVG (programmatically), then pushing that png file into the canvas using drawimage(), might provide some success? Something similar? Hmm...
Check out that article , but it seems there is no standard method to do what you want and it may fail in IE.
http://svgopen.org/2010/papers/62-From_SVG_to_Canvas_and_Back/#svg_to_canvas
You should perhaps go with an all SVG game , or provide a maximum zooming rate to your game and use big images as sprite assets. it would not have been a problem using flash,but i guess you wont go with flash anyway.
Maybe there is a framework that can translate SVG into a "canvas drawing sequence" but i would not bet on high performances in that case.
I managed to answer my own question.
The way to do this is to first create an SVG file, and then convert it to a PNG file on the client using "canvg". The PNG can be created at different levels of details based on what you want, and in this way you could create a dynamic LOD system.
Flash does something similar automatically by cashing a bitmap image of the SVG file... it's called "pre-rendering". If the SVG isn't scaled or the alpha isn't changed, flash will just use the bitmap instead (much faster then continuously re-rendering the SVG file, in complex cases). Size (and thus detail) of the PNG output can be modified however you like, and so pre-rendering could be done based on events as well.
From this information, I have decided to implement the LOD system such that SVG is used whilst the user is actively zooming (scaling the target "sprite"), and then as the zoom slows down, compute a PNG pre-render. Also, at extremely high levels of zoom, I simply use the SVG, as it is much easier for the CPU to compute SVG's at high resolution, then bitmap images that cover most of the screen. (just take a look at some of the HTML5 icon tests that put lots of icons on the screen... the bigger the icons are, the slower it runs).
Thanks very much to everyone's comments here and I hope that my question/answer has helped someone.

Redraw lots of objects on Canvas HTML

Is there a quick and efficient way to move lots of objects in canvas? Basically if there are around 1000 objects and I want to move all of them at once to emulate scrolling, it is very slow to redraw every single object by calling drawImage() 1000+ times.
Is there anyway to optimize this? I have an example link of the problem (and that's only with 100 objects): http://craftyjs.com/isometric/
Since canvas doesn't provide fast low level bitmap copying it's hard to do stuff in multiple layers and scroll for example the whole background at once and then only render the edges.
So what can you do? In short, nothing. Especially not when scrolling, sure you can do tricks with multiple canvases when you have a more or less static background but for moving objects there are hardly any performance improving tricks.
So, you've go to wait for Hardware Acceleration shipping in all majors browsers, I know this sounds ridiculous but I'm too waiting for that :/
The problem is that the canvas was never designed for game stuff. It was designed as, well, basically some kind of on the fly drawing thing, guess the designers had Photoshop clones in mind, but definitely not games, let alone the fact that there's no fast clear operation proves that, there's not even optimization in place when clearing the whole canvas with the same color.
If the images are already composited, not moving relative to one another, and defined by a rectangular region, then using canvas.drawImage() with a canvas as the first parameter and drawing to a sub-region should be significantly faster than re-drawing all the objects.
You could also just layer multiple canvases and slide the top canvas with the objects in HTML to scroll them.
Edit: Having really looked at your example, it seems to me that it should be implemented similar to Google Maps: create tiles of canvases and slide them left/right on the HTML page; once a canvas has been slid off the screen entirely (for example, off the left edge), move it to the other side (to the right edge) and re-use it for drawing. With this you will only need to re-draw whatever objects overlap the canvases that are moving on the edges.
You can draw all objects on a second, off-screen canvas and then only blit the whole canvas (drawImage() accepts canvas element).
However, if you're targeting desktop browsers, then this shouldn't be necessary. I've implemented tile engine (source) that simply redraws whole scene and naive implementation turned out to be pretty fast.
What I did to solve this problem was I had 10 squares on my screen and I wanted to animate them on a white background. So I drew a white rectangle over the canvas to clear the canvas so the animation would work. Does that make sense?
#Ivo By the way I read on http://www.w3.org/TR/html5/the-canvas-element.html that canvas was made for applications like games because it was a solution to get rid of the dependency on a external engine. Canvas is built in so it's kind of like a flash player built into your browser powered by JavaScript. I think it's fascinating.
You can use tiled rendering.
http://www.gamesfrommars.fr/demojsv2/ (better viewed with Chrome)

Categories

Resources