what is it that you can do with canvas and not with SVG? - html

I am working on project I need to choose between the SVG and Canvas. I am finding SVG best at most of the things.
Are there anythings that you can not do with the SVG but you can with Canvas?

First,
If you already have invested time in the SVG learning curve, you might well complete your project without Canvas because these 2 elements do remarkably similar things. Canvas has a fairly large & steep learning curve that you might want to avoid "mid-project".
Contrary to popular opinion...Both Canvas and SVG use vector drawing commands!
They use vector commands to paint lines and curves on their drawing surfaces. Both Canvas and SVG render those drawings onto their element surfaces as pixels.
And...
Both Canvas and SVG can transform (offset, rotate and scale) their drawings. Both Canvas and SVG can apply style to their drawings (fill color, stroke color, opacity, etc).
But...
SVG goes one step further and "remembers" all the drawing commands. This means SVG can reissue those drawing commands even when scaling. So SVG is ideal for drawings that must be scaled without becoming "jaggy". You can even use CSS to re-style your drawings (change colors, opacity, position, rotation, etc). That's often very useful. For example, you can make an SVG leopard change the color of its spots with CSS!
Canvas just "draws and forgets" -- it remembers nothing about what or where it's drawn. As such, it's a lighter element. You say: "But canvas does all those games with moving players". With canvas, the programming practice is to erase the canvas and redraw any shapes in their new positions. This gives the illusion that the shapes are being commanded to move (which they are not). Canvas is built to be extremely fast at these redraws and will easily redraw modestly complex game scenes at 60 frames per second. This speed comes at the cost. You must "remember" where your scene elements are so you can later re-render them in their new positions and with their new stylings. (No simple CSS ability to make a canvas leopard change its spots).
SVG drawings come with the traditional mouse events already built in. Canvas only fires the traditional mouse events on the canvas as a whole and not on individual drawings (because canvas forgets about the shapes it's drawn). Therefore, if you want to get mouse events related to an individual canvas shape you must (1) Remember where you drew your shapes (2) listen for the mouse event on the whole canvas, (3) check if the mouse is inside any shape (this is easily done mathematically) and then handle the mouse event for your discovered shape. Canvas elements require more code to impliment.
IMHO, one particular use-case where canvas shines:
In addition to these functional differences, Canvas lets you examine and change any pixel on the canvas surface. In particular, this valuable pixel information lets you do some nice tasks with images:
Recolor any part of an image at the pixel level (if you use HSL you can even recolor an image while retaining the important Lighting & Saturation so the result doesn't look like someone slapped paint on the image),
"Knockout" the background around a person/item in an image,
Detect and Floodfill part of an image (eg, change the color of a user-clicked flower petal from green to yellow -- just that clicked petal!),
Do Perspective warping (e.g. wrap an image around the curve of a cup),
Examine an image for content (eg. facial recognition),
Answer questions about an image: Is there a car parked in this image of my parking spot?,
Apply standard image filters (grayscale, sepia, etc)
Apply any exotic image filter you can dream up (Sobel Edge Detection),
Combine images. If dear Grandma Sue couldn't make it to the family reunion, just "photoshop" her into the reunion image. Don't like Cousin Phil -- just "photoshop him out,
Play a video / Grab a frame from a video,
Export the canvas content as a .jpg | .png image (you can even optionally crop or annotate the image and export the result as a new image),
Many more image pixel manipulations that haven't come to mind!

Canvas is a pixel manipulation element.
SVG is vector element container.
I feel distinction between these two is outside the scope of StackOverflow to dicuss, as it is related to computer art basics, not programming and there is a lot of information available if not in search engines then in WikiPedia. For example one would use pixel-based media for pixel games.

Related

Isometric canvas/SVG HTML 5 images

I'm seeking some tutorials, how I make canvas or SVG (not sure which) images in an isometric map for a RTS game purpose. The images should only be clickable on the visible part, otherwise the user should be clicking on the background image. It can either be done by auto detecting transparent areas of PNG or from color overlay. I have no idea which is best.
Thanks.
If you won’t be changing the perspective of your scene, then I would go with SVG because they are DOM elements (clickable out-of-the-box) and you can limit the click area to the non-transparent part of the element. A very good SVG library is RaphaelJS.
The canvas is a different kind of animal. The vectors/rasters you draw on a canvas are not “retained”, meaning unlike SVG, you cannot instruct the box you just drew on the canvas to move. Instead, you are in charge of redrawing that box where you want it. After you draw everything on your canvas, it is basically becomes a big bitmap. If your scene’s perspective will be changing, you might need what canvas does best: speed and flexibility. Using matrix transforms, you can do 2D movement, rotations, scalings and skews. Since you are in charge of the transformation matrix, you can also simulate 3D movement. If your users have non-IE browsers, you also have WebGL which is a full 3D imaging system. With this power comes complexity, so you will probably check out the many game development platforms available for canvas.
With both elements, you can use websockets to do your RTS (of course degrading to long-polling for browsers that don’t support websockets).

HTML 5 canvas image special effects

I'm working on a 2d tile based HTML5 canvas application and I would like to know what kind of special effects I can apply to the images as their being drawn ( context.drawImage(...) ). The only trick I've come across is modifying the canvas.globalAlpha value. This leaves some color from the previous frames, creating a blurring or dazed effect if things on the canvas object are moving from frame to frame.
Is there something for rendering images that is comparable to setting the context.fillStyle to an ARGB value for primitive shapes?
Is there a multiply mode? ie: multiply the image pixel color by the destination color. This could be used for primitive lighting. (I've toyed around with context.globalCompositionOperation but didn't find anything interesting)
Are there any other cool effects you've come across?
NOTE: I don't want to use WebGL for this application, and it's a game. That means it's realtime and I can't modify each pixel with javascript code because that takes too long. (although I could probably do that when the player dies and nothing is moving on the screen anymore)
Canvas doesn't provide any predefined effects.
To manipulate the image shape you can use matrix transformations.
To manipulate the image pixels and colors you should use getImageData method - http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#pixel-manipulation.
Then use google to find algorithms to apply some effects like swirl, blur, emboss etc.

Diagrams in SVG versus HTML5 Canvas

I want to start a project where I need to draw diagrams consisting of rounded rectangles connected with lines and a JavaScript action when I click some elements. This needs to work in all modern browsers.
Both SVG and HTML5 Canvas seem to be able to do this so I wonder what would be best.
Also I don't want to reinvent the wheel, so if there are libraries that do such things I would like to know; I took a look at Raphaël and some other JavaScript drawing libraries but they don't give all the functionality I need. In Google's API there is such a tool but it is very limited.
Use SVG because—as a retained-mode drawing API—you can attach event listeners directly to specific elements, and change properties of specific elements and have the page magically update. Further, as a vector-based format, it is resolution-independent.
HTML5 Canvas, by comparison, is a non-retained-mode (aka immediate-mode) drawing API; every pixel you draw is blended with all other pixels on the canvas, with no concept of the original shape. Further, as a raster-based format, you would need to do some extra work to get the drawing commands to adjust for different display sizes.
In general, you should use Canvas if and only if you need:
Direct setting of pixels (e.g. blurs, sparkly effects), or
Direct getting of pixels (e.g. reading a user's drawing to save as a PNG, sampling portions of the image to detect visual overlaps), or
massive number of 'objects' that won't move much or track individual events (SVG can be slow to redraw with thousands of objects).
Note also that you don't have to choose only one or the other. You can draw SVG onto canvas. You can include bitmaps (images) in SVG. You can even include HTML5 Canvas in SVG via <foreignElement>. You can have a single HTML page with multiple layered canvases and SVG elements with transparent backgrounds, intermingling the output of each.

Clear Canvas Rect (but keep background)

I'm trying to animate a circle and just moving it horizontally which works fine. However while the circle is moving, I have to do a clearRect over that circle so that it redraws it self in the horizontal direction. When I do a clearRect it also makes the background have white box around so effectively its going to be one white horizontal line in the direction the circle is moving.
Is there a way to clear the circle without clearRect?
If I have to keep redrawing the background after clearRect the canvas will flicker when theres say 10 circles moving in that area.
Any other approaches to solving this?
function drawcircle() {
clear();
context.beginPath();
context.arc(X, Y, R, 0, 2*Math.PI, false);
context.moveTo(X,Y);
context.lineWidth = 0.3;
context.strokeStyle = "#999999";
context.stroke();
if (X > 200)
{
clearTimeout(t); //stop
}
else
{
//move in x dir
X += dX;
t = setTimeout(drawcircle, 50);
}
}
function clear() {
context.clearRect(X-R, Y-R, 2*R, 2*R);
}
Basics: HTML5 Canvas as a Non-Retained Drawing Mode Graphics API
First, let us discuss the manner in which the HTML5 Canvas works. Like a real-world canvas with fast-drying oil paints, when you stroke() or fill() or drawImage() onto your canvas the paint becomes part of the canvas. Although you drew a 'circle' and see it as such, the pixels of the circle completely replaced the background (or in the case of anti-aliasing at the edges of the circle, blended with and forever changed them). What would Monet say if you asked him to 'move' one of the people in a painting a little bit to the right? You can't move the circle, you can't erase the circle, you can't detect a mouseover of the circle…because there is no circle, there is just a single 2D array of pixels.
Some Options
If your background is fully static, set it as a background image to your canvas element via CSS. This will be displayed and overlaid with content you draw, but will not be cleared when you clear your canvas.
If you cannot do the above, then you might as well just clear the entire canvas and re-paint it every frame. In my tests, the work needed to clear and redraw just a portion of the canvas is not worth the effort unless redrawing the canvas is very expensive.
For example, see this test: http://phrogz.net/tmp/image_move_sprites_canvas.html
In Safari v5.0.4 I see 59.4fps if I clear and re-draw the entire canvas once per frame, and 56.8fps if I use 20 clearRect() calls and 20 drawImage() calls to re-draw just the dirtied part of the background each frame. In this case it's slower to be clever and keep track of small dirty regions.
As another alternative, use a retained-drawing graphics system like SVG or HTML. With these, each element is maintained independently. You can change the position of the item and it will magically move; it is up to the browser to intelligently draw the update in the most efficient manner possible.
You can do this while retaining the power of custom canvas drawing by creating and layering multiple canvases in the same HTML page (using CSS absolute positioning and z-index). As seen in this performance test, moving 20 sprites via CSS is significantly faster than trying to do it all yourself on a single canvas.
Flickering?
You wrote:
If I have to keep redrawing the background after clearRect the canvas will flicker when theres say 10 circles moving in that area.
That has never been my experience. Can you provide a small example showing this 'flicker' problem you claim will occur (please specify OS, browser, and version that you experience this on)? Here are two comments by prominent browser developers noting that neither Firefox nor Safari should ever show any flickering.
This is actually very easy to accomplish by simply positioning more than one canvas on top of each other. You can draw your background on a canvas that is (wait for it...) in the background, and draw your circles on a second canvas that is in the foreground. (i.e. stacked in front of the background canvas)
Multiple canvases is actually one of the best ways to increase performance of anything animation where elements of the final image move independently and do not not necessarily move in every frame. This allows you avoid redrawing items that have not moved in every frame. However, one thing to keep in mind is that changing the relative depth (think z-index) of items drawn on different canvases now requires that the actual <canvas> elements be reordered in the dom. In practice, this is rarely an issue for 2D games and animations.
Contrary to what the accepted answer suggests; yes, you can restore previous draw states, and contrary to what the other answers imply; no, you don't need additional canvases to do so:
The CanvasRenderingContext2D API includes the functions getImageData() and putImageData(). After creating a background image, store the whole thing in a variable const background = context.getImageData(x, y, width, height) (a simple RGBA bitmap of type Uint8ClampedArray), then after wiping the canvas with clearRect() or whatever, restore the background image simply by passing that variable back in the opposite direction: context.putImageData(x, y, background).
There are two ways you can do it that may reduce the flickering, esp if you have many circles.
One is double buffering, and for a brief question on this you can look at:
Does HTML5/Canvas Support Double Buffering?
Basically, you draw on two canvases, and swap them in and out as needed.
This would be the preferable option, esp with many changes per frame, but, the other way I have done this is to just draw over the circle I want to erase, using the background color, then draw with the correct color the new circle.
The only problem is that there is a small chance that you may leave some evidence of the attempted erasing, as it seems that for some shapes it is hard to get it to draw exactly on top.
UPDATE:
Based on a comment you can look at this discussion about double buffering on the canvas:
HTML canvas double buffering frame-rate issues
The basic idea is to keep track of everything you have drawn, with the current position, then on a separate canvas, you redraw everything, then, flip them out, and then I would just redraw again, in the new positions, to ensure that the image looks exactly like it should. Swapping them in and out is a quick operation, the only problem would be if you put event handlers on the canvas, in this case, have them on the div or span surrounding the canvas, so this information doesn't get lost.

How canvas tag is beneficial in HTML5?

I am a junior developer I can't understand how canvas tag is beneficial for us?
I read lot of articles on that but I can't get the root benefit getting from the canvas tag.
Think of the difference between canvas and svg as the difference betwee Photoshop and Illustrator (or Gimp and Inkscape for you OSS folks). One deals with bitmaps and the other vector art.
With canvas, since you are drawing in bitmap, you can smudge, blur, burn, dodge your images easily. But since it's bitmap you can't easily draw a line and then decide to reposition the line. You need to delete the old line and then draw a new line.
With svg, since you are drawing vectors, you can easily move, scale, rotate, reposition, flip your drawings. But since it's vectors you can't easily blur the edges according to line thickness or seamlessly meld a red circle into a blue square. You need to simulate blurring by drawing intermediate polygons between objects.
Sometimes their use case overlaps. Like a lot of people use canvas to do simple line drawings and keep track of the objects as data structures in javascript. But really, they both serve different purposes. If you try to implement general purpose vector drawing in pure javascript on top of canvas I doubt you'd be faster than using svg which is most likely implemented in C.
Basically, thanks to canvas, we can now draw/render 2D shapes using HTML5 and the canvas API.
As an example of what's possible now with canvas, see this
Some possible uses for Canvas:
Image drawing program
Photo editing/manipulation
2D Games
Advanced image viewing such as Microsoft's Deep Zoom
If you can't understand how it's beneficial, then maybe it isn't from your point of view at least. Don't think that because it's there I have to use it somehow, pick and choose what technologies work for you based on what you're trying to build, an Accounting web app probably wouldn't need a canvas for instance.
The canvas will enable you to draw pixel perfect graphics.
The cool projects that came to mind for me are:
Visualize gps data. GPS data is just an XML list of coordinates. You could easily build something in canvas to "connect the dots".
An mobile app where the user can actual sign a document with her finger - canvas allows you to export out the rendered canvas drawing to PNG where it can be saved on the server.
In a game where you have avatars, you can allow the user to actual draw on the avatar. Moustaches anyone?
Other stuff:
In iOS / Android using lots of CSS3
effects like box-shadow can lead to
poor performance, especially when
animating. You can do a lot of these
graphics in a single canvas tag,
here's an example:
http://everytimezone.com/. This thing is flawless on an ipad.
Cool background effects. For example try going to Paul Irish's
site and move your cursor around the
background: http://paulirish.com/
In this HTML5 book sponsored by Google a lot of the effects are using
canvas:
http://www.20thingsilearned.com/ -
particularly the "page flip"
animations.
my personal take on canvas (and when I actually found a use case for canvas) is the ability to color pick and color change per pixel in a canvas element - actually moving the image from something we don't have any information about what is happening inside it to an element like all other DOM elements (and yes, I know about the current problems with canvas and DOM - sure this would be taken care of in the future)
sure - canvas made some sort of animation easier and pluginless, but that we could do before (mostly with flash) - I think the real importance is the ability to know what is happening on the page.