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).
Related
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.
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.
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.
What are the differences between SVG and HTML5 Canvas? They both seem to do the same to me. Basically, they both draw vector artwork using coordinate points.
What am I missing? What are the major differences between SVG and HTML5 Canvas? Why should I choose one over the other?
SVG is like a "draw" program. The drawing is specified as drawing instructions for each shape and any part of any shape can be changed. Drawings are shape-oriented.
Canvas is like a "paint" program. Once the pixels hit the screen, that is your drawing. You cannot change shapes except by overwriting them with other pixels. Paintings are pixel-oriented.
Being able to change drawings is very important for some programs; e.g. drafting apps, diagramming tools, etc. So SVG has an advantage here.
Being able to control individual pixels is important for some artistic programs.
Getting great animation performance for user-manipulation via mouse drags is easier with Canvas than SVG.
A single pixel on the computer screen will often consume 4 bytes of information and a computer screen these days takes several megabytes. So Canvas might be inconvenient if you want to let the user edit an image and then upload it again.
By contrast, drawing a handful of shapes that cover the entire screen using SVG takes up few bytes, downloads quickly, and can be uploaded again easily with the same advantages going in that direction as when it comes down on the other direction. So SVG can be faster than Canvas.
Google implemented Google Maps with SVG. That gives the web app its zippy performance and smooth scrolling.
See Wikipedia: http://en.wikipedia.org/wiki/Canvas_element
SVG is an earlier standard for drawing
shapes in browsers. However, SVG is at
a fundamentally higher level because
each drawn shape is remembered as an
object in a scene graph or DOM, which
is subsequently rendered to a bit map.
This means that if attributes of an
SVG object are changed, the browser
can automatically re-render the scene.
In the example above, once the
rectangle is drawn, the fact that it
was drawn is forgotten by the system.
If its position were to be changed,
the entire scene would need to be
redrawn, including any objects that
might have been covered by the
rectangle. But in the equivalent SVG
case, one could simply change the
position attributes of the rectangle
and the browser would determine how to
repaint it. It is also possible to
paint a canvas in layers and then
recreate specific layers.
SVG images are represented in XML, and
complex scenes can be created and
maintained with XML editing tools.
The SVG scene graph enables event
handlers to be associated with
objects, so a rectangle may respond to
an onClick event. To get the same
functionality with canvas, one must
manually match the coordinates of the
mouse click with the coordinates of
the drawn rectangle to determine
whether it was clicked.
Conceptually, canvas is a lower level
protocol upon which SVG might be
built.[citation needed] However, this
is not (normally) the case—they are
independent standards. The situation
is complicated because there are scene
graph libraries for Canvas, and SVG
has some bit map manipulation
functionality.
UPDATE:
I use SVG because of its markup language abilities - it can be processed by XSLT and can hold other markup in its nodes. Similarly I can hold SVG in my markup (chemistry). This allows me to manipulate SVG attributes (e.g. rendering) by combinations of markup. This may be possible in Canvas but I suspect that it's a lot harder.
High Level Summary of Canvas vs. SVG
Canvas
Pixel based (Dynamic .png)
Single HTML element.(Inspect element in Developer tool. You can see only canvas tag)
Modified through script only
Event model/user interaction is granular (x,y)
Performance is better with smaller surface, a larger number of objects (>10k), or both
SVG
Shape based
Multiple graphical elements, which become part of the DOM
Modified through script and CSS
Event model/user interaction is abstracted (rect, path)
Performance is better with smaller number of objects (<10k), a larger surface, or both
For detailed difference, read http://msdn.microsoft.com/en-us/library/ie/gg193983(v=vs.85).aspx
There's a difference in what they are, and what they do for you.
SVG is a document format for scalable vector graphics.
Canvas is a javascript API for drawing vector graphics to a bitmap of a specific size.
To elaborate a bit, on format versus API:
With svg you can view, save and edit the file in many different tools. With canvas you just draw, and nothing is retained about what you just did apart from the resulting image on the screen. You can animate both, SVG handles the redrawing for you by just looking at the elements and attributes specified, while with canvas you have to redraw each frame yourself using the API. You can scale both, but SVG does it automatically, while with canvas again, you have to re-issue the drawing commands for the given size.
Two things that hit me the most for SVG and Canvas were,
Ability to use Canvas without the DOM, where as SVG depends heavily on DOM and as the complexity increases the performance slows down. Like in game design.
Advantage of using SVG would be that resolution remains the same across platforms which lacks in Canvas.
Lot more detail is provided in this site. http://dev.opera.com/articles/view/svg-or-canvas-choosing-between-the-two/
It is absolutely depends on your need/requirement.
If you want to just show an image/chart on a screen then recommended
approach is canvas. (Example is PNG, GIF, BMP etc.)
If you want to extend the features of your graphics for example if you
mouse over on the chart want to zoom certain area without spoil
display quality then you select SVG. (Good example is AutoCAD, Visio,
GIS files).
If you want build a dynamic flow diagram creator tool with shape connector it is better to select SVG rather than CANVAS.
When the size of the screen increases, canvas begins to degrade as
more pixels need to be drawn.
When the number of objects increases on the screen, SVG begins to
degrade as we are continually adding them to the DOM.
Also please refer : http://msdn.microsoft.com/en-us/library/gg193983(v=vs.85).aspx
SVG
Based on use case SVG is used for logos, charts because its vector graphics you draw and forgot about it. When view port change like re-sizing(or zoom) it will adjust itself and no need to redraw.
Canvas
Canvas is bitmap (or raster) it done by painting of pixels to the screen. It is used to develop games or graphics experience (https://www.chromeexperiments.com/webgl) in a given area it paints pixel and changes by redraw it another. Since its a raster type we need to redraw entirely as view port changes.
Reference
http://www.sitepoint.com/7-reasons-to-consider-svgs-instead-of-canvas
http://en.wikipedia.org/wiki/WebGL
http://vector-conversions.com/vectorizing/raster_vs_vector.html
SVG is a specification of a drawing like a file format. A SVG is a document. You can exchange SVG files like HTML files. And additionally because SVG elements and HTML elements share the same the DOM API, it is possible to use JavaScript to generate a SVG DOM in the same way as it is possible to create a HTML DOM. But you do not need JavaScript to generate SVG file. A simple text editor is enough to write a SVG. But you need at least a calculator to calculate the coordinates of the shapes in the drawing.
CANVAS is just a drawing area. It it necessary to use JavaScript to generate the contents of a canvas. You can not exchange a canvas. It is no document. And the elements of the canvas are not part of the DOM tree. You can not use the DOM API to manipulate the contents of a canvas. Instead you have to use a dedicated canvas API to draw shapes into the canvas.
The advantage of a SVG is, that you can exchange the drawing as a document. The advantage of the CANVAS is, that is has a less verbose JavaScript API to generate the contents.
Here is an example, which shows that you can achieve similar results, but the way how to do it in JavaScript is very different.
// Italic S in SVG
(function () {
const ns='http://www.w3.org/2000/svg';
let s = document.querySelector('svg');
let p = document.createElementNS (ns, 'path');
p.setAttribute ('id', 'arc');
p.setAttribute ('d', 'M 0.9 -0.9 a 0.8,0.4 -10 0,0 -0.9,0.9');
s.appendChild (p);
let u = document.createElementNS (ns, 'use');
u.setAttribute ('href', '#arc');
u.setAttribute ('transform', 'rotate(180)');
s.appendChild (u);
})();
// Italic S in CANVAS
(function () {
let c = document.querySelector('canvas');
let w = c.width = c.clientWidth;
let h = c.height = c.clientHeight;
let x = c.getContext('2d');
x.lineWidth = 0.05 * w;
x.moveTo (w/2, h/2);
x.bezierCurveTo (w*0.02, h*0.4,
w*0.4, -h*0.02,
w*0.95, h*0.05);
x.moveTo (w/2, h/2);
x.bezierCurveTo (w*(1-0.02), h*(1-0.4),
w*(1-0.4), h*(1+0.02),
w*(1-0.95), h*(1-0.05));
x.stroke();
})();
svg, canvas {
width: 3em;
height: 3em;
}
svg {
vertical-align: text-top;
stroke: black;
stroke-width: 0.1;
fill: none;
}
canvas {
vertical-align: text-bottom;
}
div {
float: left;
}
<div><svg viewBox="-1 -1 2 2"></svg>VG</div>
<div>CANVA<canvas></canvas></div>
As you can see the result is almost the same, but the JavaScript code is completely different.
SVG is created with the DOM API using createElement, setAttribute and appendChild. All graphics are in the attribute strings. SVG has more powerful primitives. The CANVAS for example has nothing equivalent to the SVG arc path. The CANVAS example tries to emulate the SVG arc with a Bezier curve. In SVG you can reuse elements in order to transform them. In the CANVAS you can not reuse elements. Instead you have to write a JavaScript function in order to call it twice. SVG has a viewBox which allows to use normalized coordinates, which simplifies rotations. In the CANVAS you have to calculate the coordinates yourself based of the clientWidth and clientHeight. And you can style all SVG elements with CSS. In the CANVAS you can not style anything with CSS. Because SVG is a DOM, you can assign event handlers to all SVG elements. The elements in the CANVAS have no DOM and no DOM event handlers.
But on the other hand the CANVAS code is much easier to read. You do not need to care about XML name spaces. And you can directly call the graphics functions, because you do not need to build a DOM.
The lesson is clear: if you quickly want to draw some graphics, use the CANVAS. If you need to share the graphics, like to style it with CSS or want to use DOM event handlers in your graphics, build an SVG.
adding to the above points:
SVG is lightweight for transferring over web when compared to JPEG,GIF etc and also it scale extremely when resized without loosing the Quality.
SVG
It is Object Model-based.
Is suitable for using large rendering areas.
SVG provides any support for event handlers .
Modification is allowed through script and CSS.
SVG has Better scalability
SVG is Vector based (composed of shapes).
SVG is not suitable for Games graphics.
SVG does not depend on resolution.
SVG is capable for API animation.
SVG is suitable for printing with high quality and any resolution.
Canvas elements
It is pixel based.
Is suitable for using small rendering
Canvas does not provide any recourse for event handlers.
Modification is allowed through script only.
Canvas has poor scalability.
Canvas is Raster based (composed of a pixel).
Canvas is suitable for games graphics.
Canvas is completely dependent on resolution.
Canvas has no any API for animation.
Canvas is not suitable for printing high quality and high resolution.
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.