2D Physics engine to simulate gravity using images - javascript

I am searching for a 2D physics engine to simulate gravity using images, preferably PNG images with transparency. So the engine will know how to calculate the collision base on the opaque parts of the image. I have only found Javascript engines that works with primitive shapes and basic HTML elements, but not with images.

I don't know any way to do what you desire, but you can try drawing your shapes in HTML5 Canvas and use Box2D.js for working with shape collision.

One think you could do is compute the convex hull of your image (you can have a look here) and then use those hulls to compute collisions and so on (using GJK for example, you can find some great explanations here or here)
As noted by micnic, I guess you can indeed use Box2D.js and feed a b2PolygonShape why the non transparent pixels of your images (or you can compute their contours and use contours as input for the b2PolygonShape)

Related

Display text with WebGL

I want to display text with WebGL, and I know that there is not a built in way to do this. However, I know it can be done, with textures. I am new to OpenGL, so I don't really have much experience with shaders, so if someone could add how to set up the shaders for this. I would like to draw the entire string on the same object, instead of a bunch of seperate letters, and the strings are NOT preset, they will not always be the same. How can I get the text to appear? Also, how do I know how to space each letter?
I read post #7 at this page, and that sounds like it's what I want to do, but I don't understand exactly what It all means. (It's mostly the shader stuff I don't understand).
By the way, I am using sylvester.js
There are many ways to render text but one of the simplest is called bitmap font rendering.
All you need to get started is a sprite sheet with all of the letters you might want to render. Then you simply render a quad with the texture coordinates set to the location of the character you want to draw. To render a full sentence, just draw a bunch of quads, each representing a single letter.
Your sprite sheet will look something like the following texture.
Once you have that, you'll need the texture coordinates, essentially (x, y) coordinates in the range 0 to 1, for each character in the sprite texture. Use these when generating quad meshes. You'll end up drawing something like this to the screen:
Now that you have text on the screen, you can get fancy and take into account the glyph kerning between the letters. This allows you to render more natural text.
Unfortunately, I can't find a tutorial to point you to. And its not really something that I can whip together for you here. There are many pieces to the puzzle and its no small task (matrix math, camera's, orthographic projection, texture coords, textures, sprites, generating meshes, etc...).
If you'd like you can look through one of my projects where I have done this with WebGL. I even generate the initial sprite sheet using javascript + 2d canvas.
Sprite Sheet generated here:
https://github.com/zfedoran/prefab.js/blob/master/app/graphics/spriteFont.js
Quad Mesh generated in this file:
https://github.com/zfedoran/prefab.js/blob/master/app/controllers/labelController.js
Wrapper around WebGL:
https://github.com/zfedoran/prefab.js/blob/master/app/graphics/device.js
Or You Could
Watch Notch (the guy who made Minecraft) do this, in only about 30 minutes, in Java (fast forward to 2:21 hours in):
http://www.twitch.tv/notch/b/487451713
http://www.twitch.tv/notch/b/487621698
Good luck, and have fun :)
Three.js has actual text glyph support. In addition, dimensionthree.net uses textures on shapes. if you need source let me know.
There also is my http://taccGL.org library that can draw HTML text on a 2D canvas and then use it as textures on 3D objects drawn on a 3D/WebGL canvas.

Can this sequence be done in HTML5?

I certainly don't expect anyone to actually provide a working solution for this. My question at this point is a simple one: can this be done with an HTML5 canvas, or would I be spinning my wheels in the attempt?
I'm a programmer, but my forte is in PHP, JavaScript, traditional HTML, etc. ...I haven't had a chance to play with HTML5 yet.
The elements you see in the example, I can save out as individually as necessary. So to make the blocks rotate around the center, I was thinking I save a square image with the block in the appropriate corner, respectively. Then rotating the image would pivot around center appropriately, unless you can set a point of origin on an image a la PhotoShop.
The KineticJS library looks promising for this type of animation as well, but I'll leave the recommendations to you fine folks.
Anyway, here is the example I want to replicate:
I won't give any library recommendations for the same reasons that #Diodeus points out, but maybe I can help your selection process. What you're trying to do can be done multiple ways in the browser right now: Canvas, SVG, and/or CSS3 animations.
Your example above is basically a few vector graphics composed together with a gradient on your center "pie timer". Because of this I would lean towards using S V G, especially if you want to allow interactions with your component (each SVG element can have event handlers).
The canvas element is better for "pixel by pixel" control of your visual content on the page. Adding content in the canvas doesn't grow the DOM (like with SVG) so it will normally perform better, but you lose things like native event handlers and animations that you will end up having to re-implement on your own.
More about the choice between SVG and Canvas, and an SVG animation example
Once you have the components in the page, they'll need to be wired up and animated. The animation can be broken down into:
Scaling
Background color fading
Rotation
"Weird gradient pie timer" example with CSS3
These can be done with CSS animations, SVG animations, or with plain old javascript. The choice depends on what you'll be animating. If I was selecting a library I would want to find one that tried to use the newer methods (SVG/CSS3) when it can, and gracefully degrade when it cannot.
I would be weary of libraries that try to re-implement things that are already available natively in the browser. Relying more on the browser instead of your own code to do things like animations means that the browser can optimize its operations and use things like hardware acceleration to improve your performance.
Hopefully this can aid your library selection. Remember, libraries come and go all the time so don't get too attached to one. An ideal implementation should allow for you to easily swap out your animation or display code without having to touch other unrelated pieces.
Sure, it's not all that difficult when you break it down into pieces.
Here are some technologies and techniques to get you started.
You use Canvas by (1) displaying some drawings, (2) erasing, (3) displaying some new drawings
When you do this redrawing rapidly, you get animated effects like your image shows.
Html Canvas uses a context to draw with (think of it as the pen for the canvas)
drawing a path: context.beginPath + context.moveTo + context.lineTo will define a path that creates your "fan blade" polygons. You can use context.fillStyle to fill the polygons with you colors.
fading: context.globalAlpha will change the opacity of new drawings
rotating: context.translate(centerX,centerY) + context.rotate(radianAngle) will rotate new drawings (like your rotating polygons, your tick-marks, )
scaling: context.translate(centerX,centerY) + context.scale(scaleX,scaleY) will scale your polygons.
arcs: context.arc(centerX,centerY,radius,beginningAngle,endingAngle) will draw an arc with a specified centerpoint and sweeping from a beginning angle to an ending angle.
math: circleCircumferenceX = centerX+radius*Math.cos(radianAngle) circleCircumferenceY = centerY+radius*Math.sin(radianAngle) uses trigonometry to calculate an xy coordinate on the circumference of a circle. You can combine this trig + Math.random to place your "speckles" in an arc around your centerpoint.

HTML5 SVG vs Canvas for big number of lines?

Question:
Is canvas more suitable than svg in the following case?
Case:
I'm drawing a chart (using d3js library) similar to this one (but with much more data):
http://mbostock.github.com/d3/talk/20111116/iris-parallel.html
It's based on an svg and it works fine for several thousands of lines (up to 5000), adding more lines (svg path) decreases the performance dramatically (scrolling in the page becomes slow)
Keep in mind: That I need to add mouse events (which is handy in svg)
Generally svg is better suited for vector images, like in your example. However canvas has a lot of benefits in modern browsers such as hardware acceleration, so for drawing the lines, as long as zooming, panning ect. isn't required performance will be using canvas.
Mouse events can be a pain using canvas, since you have to manually keep track of everything, so with 5000+ points using canvas it wont be fun. The trade off however will be once the points are drawn, assuming you only draw them once the page will behave fine regardless of the number of lines, since they are all drawn to a raster image and aren't part of the DOM.
Honestly though the best way to find it is to test what you currently have using canvas.
When performance becomes a problem, switching to canvas might be an option. In this case you can draw the canvas once. Afterwards it's pretty much treated like an image. Drawing might take some time, but afterwards it can be scaled pretty quickly. Note that it is possible to draw a rendered SVG to a canvas using the context.drawImage method (example). So you could keep your SVG generation code to create an SVG in the background, and then draw it to the canvas.
But keep in mind that it won't scale as beautiful as an SVG as soon as it is on the canvas. When the user zooms in, it will get blurry or pixely, depending on how the browser scales graphics.
Click events on canvas can be handled in two ways. Either keep an array of click targets, and add an onclick event handler to the canvas. When a click occurs, iterate the array and check which one is closest to the click coordinates.
The other option is to use hit regions. These have to be defined as polygonal paths.
+1 to everything said above. I've seen some amazing performance increases when using canvas over SVG and over compositing images using the DOM.
About manipulating the canvas image with mouse events, I imagine the best approach for an image such as you are describing is to abstract it away using a library like the following:
http://paperjs.org
http://kineticjs.com
http://www.createjs.com/#!/EaselJS
Keep your code away from the canvas itself and let a library do the thinking for you.

clip-path in Raphaël.js

How can I use clip-path with Raphaël.js like this example. It seams that Raphael.js has only clip-rect in it.
You can cut a hole through a path drawn shape.
This is a technique known as donut holes and you can see an example on my index page
If this looks difficult it is not
See the information database and the technique labelled donut holes
My site index is
http://www.irunmywebsite.com/
Err it used to be.
Now you can find a multiple clip path (Imagine seeing a view through several holes}
The carousel and the thumbnail holder are just one path...
See the Raphael Crousel
A much better example I include below. The central blue region has several holes cut into it. This has multi purpose usage.
It is part of what I call a DOM / SVG hybrid solution.
Cut multi purpose holes for a variety of reasons
I don't think you can do it via Raphael. You can do it by manipulating the DOM directly, but you will loose the ability to call Raphael methods for that element.
I find Raphael a bit obsolete, now that IE supports SVG. You can do much more with plain javascript and and the SVG specification.
If, like in the example image, it's a raster image (png, gif, jpg... bitmap pixel images) you are trying to clip, it's actually really easy. In Raphael 2, you just set the fill to point at the image file. It uses it as a background image.
If you want to crop an image or photograph with a Raphael path or shape like a clipping mask or clip-path for image files, just set the image as the path's fill.
somepath.attr({fill: 'someimage.png'});
Limitations (AFAIK):
Only one image per path
Only one path per image (use compound paths for complex masks)
Things like background position aren't easy - see this question for more
I think it's impossible to stop the image repeating

What is the real benefit of using canvas for games?

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.

Categories

Resources