Multiple Canvas Board Game vs. Single Canvas - javascript

I am new to programming games. I'm just wondering, so for a simple board game (let's say Tic Tac Toe or Checkers), would it be a good idea to use multiple canvas for the board? I mean, each canvas could represent each square on the board.
I feel that many people tend to do it like this because it keeps the logic simple. You let the CSS do all the spacing and annoying square separation. But I don't know if it's good practice to do it like that.
Since I am new, I feel that avoiding shortcuts now will be beneficial when I create something complex. So, what's your take on separate canvas for each board square?

The most important thing is to find a balance and understand why you would use one canvas versus layered canvases.
For a tic-tac-toe game only one is needed as there is nothing there that needs constantly updates. If would be easier to maintain as well. Event-driven (ie. nothing happens until you click/do something) games/apps such as this would typically not benefit from several layers.
When you use more than one canvas it is usually because you have a static or complex background (or foreground for that matter), and some objects moving over it that needs to move smoothly. This would be a good candidate for layering canvases as this allow you to clear and redraw only the region of the moving object instead of rendering the background as well (particular in cases where the background is a composite).
It's not much more complex to handle layered canvases than one, but you would need to keep track of where you do the draw operations. You can use objects with embedded information to do this, or for extra performance use arrays/variables.

Related

What is a high performance way of splitting up Sprite Sheets/ Chip Sets in JS?

I'm working on a 2d world editor for html/js, and trying to find the best way to split up a chip set (as seen below) into multiple little squares (chips).
Currently, I'm using a method similar to the default css sprite sheets method, of using background position to move the background of many little <div> elements until each displays one square/chip of the chip set.
It is working fine, with no big performance issues, but it seems like an overall clunky way to do it.
Other ways I've thought of doing it would be to slice the chip set into many temporary images and make an <image> element for each, or using <canvas> instead of <div>'s or <image>'s
Anyways, I'm looking for advice on the subject:
What is a high performance way of splitting up Sprite Sheets/ Chip Sets in JS?
example of a chip set
The way you're doing it right now should be pretty fast. You could essentially reimplement that on the canvas level by storing just the one image then using drawImage to only draw sections from it. To the best of my knowledge, this is the most common way and is very fast. At least that was my experience when I wrote a game engine using canvas.
Using the canvas is most likely faster and more memory efficient since you don't have the additional DOM overhead but you'd have to measure it for your specific use case and verify that.
Creating a bunch of individual images, as you suggested, would be very slow since it'd require copying portions of the image and creating an additional DOM element for each image.
In short: using the canvas will always be faster (for a comparable implementation) since you're almost directly interfacing with the GPU. Drawing from one image rather than copying it into multiple sub images will always be faster since you won't have duplicate memory sitting around and as long as you're drawing from the same sheet, the GPU doesn't have to switch out the texture.

HTML5 Game, canvas or div?

I am planning on creating a real-time multiplayer platformer game in HTML5 using javascript. After searching about 4 hours on the webs, i couldn't find an up-to-date answer on the eternal question: rendering my game with DOM will be faster than rendering it inside a canvas? The game will be the whole document. 2/4 players will be jumping on the map and will shoot at each other, bombs will explode. So? What will it be. I remember I made 2 years ago a draw application with DOM and it worked kinda smoothly, but i guess canvas speed is better nowadays? Thank you guys.
P.S. I think of using Dart too.
I use canvas, and would say to do the same since it's a direct drawing mode. However, you should absolutely make sure it is forced into hardware acceleration wherever possible. You do this by setting the style of the <canvas> element into transform:translateZ(0); (or different browser interpretations of that, e.g. -webkit-transform:translateZ(0);). Manipulating the DOM can be slow now that canvas is closer and closer to native code, especially with simple methods to get the most performance out of it.
My games seem to do pretty well on different platforms with this - not universally well on every single platform (older Android OSes lag, but their JS & browser rendering engines weren't that fast to begin with), but quite well on many platforms.
Canvas is the best choice for the type of game you are describing, but some DOM elements are still very useful even using canvas, for example, asking the player's name, or creating a menĂº or profile section inside the game. You can render a div with absolute position on top of your canvas when you need to display DOM elements, and do all the "game stuff" like drawing and animate sprites in the canvas element.
The reason why Canvas is the best choice is simple. I'm pretty sure that you can't or it would be really hard to do things like this without the canvas element:
http://galloman.github.io/ss2d/samples/skeletons2.html
More at: http://ss2d.wordpress.com/support/

Is it better to have one big canvas or up to 100 small dynamically generated canvases?

I am working on a mobile web dice simulator. The initial prototype is here: http://dicewalla.com
I currently have one large canvas where I draw all the dice. I am planning to re-write the code in way that is more MVC and easier for me to update. I think it would be easier for me to generate a small canvas for each die object than to draw all of the dice on the big canvas and keep updating that big canvas.
My question is if there is a bad performance hit in having the browser create lots of little canvases vs one big one. It's hard to test locally, I was hoping someone here might know what the best practice is.
Multiple canvases usually allow for better performance as you're able to selectively re-render.
If you have only one canvas and want to update one die, you'll typically have to redraw the entire canvas. On the other hand, multiple canvases allow you to update only the dice that need to be redrawn. That's an increase in efficiency.
Further, you shouldn't see any noticeable difference in loading 1 canvas versus 100.
In terms of performance, like was mentioned earlier, there should be little difference between 1-100 canvas elements if you're not updating the graphics on a regular basis. (ie: static graphics / no animation)
Most of the references around the net regarding multiple canvases tend to deal with cases where you have multiple layers and need to handle drawing on top of other things with transparency.
That being said, what you're doing with dicewalla doesn't look like it will gain anything from having multiple canvases.
Also you can selectively redraw the regions of a single canvas to get better performance if updating the entire canvas is a bottleneck. This gives you the performance benefits of having multiple canvases without having to deal with managing and creating those elements.

Break the scene to several canvases or keep redrawing one?

Intent on creating a canvas-based game in javascript I stand before a choice:
Should I performance-wise keep all the stuff happening in the screen in one canvas (all the moving characters, sprites) and redraw it at constant rate of, say, 60 FPS or should I break the scene into several smaller canvases thus removing the need of redundant redrawing of the scene? I could even create separate canvas elements for the characters' limbs and then do most of the animation by simply manipulating the CSS of the given canvas element (rotation, positioning, opacity).
To me the latter sounds way more plausible and easier to implement, but is it also faster? Also, shouldn't I perhaps use SVG, keep the characters and sprites as elements inside of it and manipulate their XML and CSS properties directly?
So what do you think is the most fitting solution to a scene with severals sprites and characters:
One canvas object redrawn manually (and wastefully) at FPS rate
Several canvas elements, redrawn manually in a more reasonable fashion
Structured vector graphics document like SVG / VML manipulated via DOM
I am mainly concerned about the performance differences, but the legibility of the logical code behind is also of interest (I, having already worked with canvas before, am for example fairly sure that the redrawing function for the entire canvas would be one hard-to-maintain beast of a script).
DOM manipulations are slow in comparison to GPU-accelerated canvas operations, so I would stay away from SVG and VML.
As far as structuring your canvas code goes, it certainly doesn't make sense (especially for performance reasons) to clear and re-draw the entire canvas because the player moved or performed an action. Based on your description here, I'm guessing that your game will be 2D. These types of games lend themselves extremely well to layering unless you're doing something rather complex like Paper Mario. You should be looking at the issue from an object-oriented viewpoint and encapsulating your drawing procedures and objects together as appropriate.
For instance, create a player object that maintains a small canvas representing the character. All the logic needed to maintain the character's state is kept within the object and any changes made to it need not worry about other components of the game's visual representation. Likewise, do the same for the background, user interface, and anything else you can abstract into a layer (within reason). For example, if you're doing a parallax game, you might have a foreground, background, character, and user interface layer.
Ultimately you will need to maintain the state of the different components in your game individually. Player animations, background clouds moving, trees swaying, etc. will all be managed by appropriate objects. Since you will already have that type of code structure setup, it makes sense to just maintain major components on separate canvas elements and composite them together as needed for better performance. If the character moves in the bottom left corner of a scene with a static background, you don't need to re-draw the top right corner (or 95% of the scene, for that matter). If you're considering full-screen capabilities, this is definitely a performance concern.
There's a rule in programming, that you should never try and optimize something before you have a speed problem with it. You'll spend more time trying to figure out how to code something in the best way than to actually code, and will never finish anything.
Draw them all on your canvas at a fixed rate. That's how it's done. If you start creating a canvas for each limb and element and manipulate them using CSS, you're wasting the potential of canvas. Might as well just use images. That's how they did it before canvas. That's the problem canvas was made to solve.
If you ever encounter speed issues, then you can start hammering at them. Check out these slides for some tips (related video). This guy's blog also has some handy tips on canvas performance.

Approach comparison: EaselJS vs Multiple Canvases vs Hidden Canvas for interactiveness

1.) I found a canvas API called EaselJS, it does an amazing job of creating a display list for each elements you draw. They essentially become individually recognizable objects on the canvas (on one single canvas)
2.) Then I saw on http://simonsarris.com/ about this tutorial that can do drag and drop, it makes use of a hidden canvas concept for selection.
3.) And the third approach, a working approach, http://www.lucidchart.com/ , which is exactly what I'm trying to achieve, basically have every single shape on a different canvas, and use to position them. There's a huge amount of canvas.
The question is, what is the easiest way to achieve interactive network diagram as seen on http://www.lucidchart.com/
A side question is, is it better to get text input through positioning on canvas or using multiple canvas (one for rendering text) as in LucidChart
I'm the person who made the tutorials in 2. There's a lot going on here, so I'll try to explain a bit.
I use a hidden canvas for selection simply because it is easy to learn and will work for ANY kind of object (text, complex paths, rectangles, semi-transparent images). In the real diagramming library that I am writing, I don't do anything of the sort, instead I use a lot of math to determine selection. The hidden-canvas method is fine for less than 1000 objects, but eventually performance starts to suffer.
Lucidchart actually uses more than one canvas per object. And it doesn't just have them in memory, they are all there the DOM. This is an organizational choice on their part, a pretty weird one in my opinion. SVG might have made their work a lot easier if thats what they are going to do, as if seems they are doing a lot of footwork just to be able to emulate how SVG works a bit. There aren't too many good reasons to have so many canvases in the DOM if you can avoid it.
It seems to me that the advantage of them doing it that way is that if they have 10,000 objects, when you click, you only have to look at the one (small) canvas that is clicked for selection testing, instead of the entire canvas. So they did it to make their selection code a little shorter. I'd much rather only have one canvas in the DOM; their way seems needlessly messy. The point of canvas is to have a fast rendering surface instead of a thousand divs representing objects. But they just made a thousand canvases.
Anyway, to answer your question, the "easiest" way to achieve interactive network diagrams like lucidchart is to either use a library or use SVG (or an SVG library). Unfortunately there aren't too many yet. Getting all the functionality yourself in Canvas is hard but certainly doable, and will afford you better performance than SVG, especially if you plan on having more than 5,000 objects in your diagrams. Starting with EaselJS for now isn't too bad of an idea, though you'll probably find yourself modifying more and more of it as you get deeper into your project.
I am making one such interactive canvas diagramming library for Northwoods Software, but it won't be done for a few more months.
To answer the question that is sort-of in your title: The fastest method of doing interactiveness such as hit-testing is using math. Any high-performance canvas library with the features to support a lot of different types of objects will end up implementing functions like getNearestIntersectionPoint, getIntersectionsOnRect, pathContainsPoint, and so on.
As for your side question, it is my opinion that creating a text field on top of the canvas when a user wants to change text and then destroying it when the user is done entering text is the most intuitive-feeling way to get text input. Of course you need to make sure the field is positioned correctly over the text you are editing and that the font and font sizes are the same for a consistent feel.
Best of luck with your project. Let me know how it goes.
Using SVG (and maybe libraries as Raphael)!!
Then any element can receive mouse events.

Categories