Anyone knows the algorithm for this kind of rubbery effect? - javascript

I'm doing some animations and I want to implement something like this on the web. I was thinking that the HTML canvas can do this kind of job. Because I can scale part of an image. I just need the algorithm to actually make it work.
The effect is elastic, if the window is small, the greater the elasticity of the window when you restore it. I was thinking that I can make this work in web images.. if the user click the image it will scale with this kind of effect, not the boring way of scaling.
This is ubuntu, I know that we can look at the source code maybe to see how it actually implements the animation. But I dont know where to find it. Or i don't even understand codes written in linux because I just understand php, javascript. Basically I'm not a software developer, My core expertise is in web development.
http://www.youtube.com/watch?v=hgQP-aFragQ

I believe your best bet is having a look at John Resig's Processing.js.
Processing is a animation language for Java; John has ported it to the browser using canvas.

Your not going to find a web based solution that is going to do this for you. If you need something like this done it will have to be in flash or some other application (Lenni mentioned Java) that runs in a separate media box embedded in a web page.
People don't want big flashy animations, seeing something that is 'boring' is much better if it becomes more usable.

First up - I don't know the actual algorithm they use here.
However, I'd attack this by creating a grid of points (say 10x10), each point attached to it's neighbors by damped springs. It might be worth anchoring the edge/corner points to the screen with springs too.
By deforming the grid (stretching and compressing the springs) and then modeling the spring responses, you'd get some interesting effects like those shown. You might then be able to record the patterns so that the points can follow a pre-computed path for faster animation if your animations are predictable.
Then you need to work out how to split the image and map it onto the grid. The splitting may be better done once on the server, but the client can do it if you use canvas.
svg & vml is a possibility - they'll work without plugins and are similar enough to code for, but I don't think you'll get correct enough image deformation. However, you can scale and rotate with impunity (and quickly) so if you just anchor 2 cell image points to the grid rather than all 4, you'll get an interesting animation - not quite like the video, but pretty good.
As for how to model damped springs, you'll need to keep track of the mass of each point (how heavy it is), how much force the spring is exerting on each point (scalar of how compressed/stretched it is and it's vector) and a damping force on the points (resistive force to the square of the velocity of the point).
It's physics modeling, to be sure, but quite possible.
The response may well be slow. Especially on IE. Canvas needs a plug-in on IE, so if you use canvas, IE folk wont see it. SVG works on almost everything except IE, but it does have VML which is similar. http://raphaeljs.com/ is a library that uses whatever's available. This will be a challenge to tune up :)
However you do this, it will always look best in chrome, the V8 javascript engine outstrips everything else for this kind of work. IE has the slowest javascript engine.

Related

Full width video background: A non-HTML5, purely jQuery solution...maybe

Long time Stack Overflow creeper. This community has come up with some incredibly elegant solutions to rather perplexing questions.
I'm more of a CSS3 or PHP kinda guy when it comes to handling dynamically displayed content. Ideally someone with a solid knowledge base of jQuery and/or Javascript would be able to answer this one best. Here is the idea, along with the thought process behind it:
Create a Full Screen (width:100%; height:auto; background:cover;) Video background. But instead of going about using HTML5's video tag, a flash fallback, iFrame, or even .GIF, create a series of images, much like the animation render output of say Cinema4D, that if put together in sequential order create a seamless pseudo-video experience.
In Before "THAT's JUST A .GIF, YOU'RE AN IDIOT" Guy.
I believe jQuery/Javascript could solve this. Would it or would it not be possible to write a script that essentially recognizes (or even adds) the div class of an image, then sets that image to display for say .0334ms (29.7 frame rate) then sets this image back in z space while at the same time firing in the next image within the sequential class order to display for another .0336ms; and so on and so forth until all of the images (or "frames") play out seamlessly fluid, so the user would assume he/she is actually seeing a video. Not a knowing it's actually a .GIF on steroids.
Here's a more verbose way of explaining the intended result:
You have a 1 second super awesome 1080p video clip (video format doesn't matter for helping to answer this question, just assume its lossless and really pretty k?). It's recorded at 29.97 frames per second. Break each frame into it's own massive image file, leaving you with essentially 30 images. 24 frames a second would mean you'd have 24 images, 60 frames per second would mean you'd have 60 images, etc., etc., excedera.
If you have ever used Cinema4D, the output I am looking to recreate is reflexive to that of an animation render, where you are left with a .TIFF per frame, placed side by side so that when uploaded into Photoshop or viewed in Quicktime you get a "slideshow" of images displaying so fast it look likes a video.
HTML would look something like this:
<div id="incredible-video">
<div class="image-1">
<img source=url('../movie/scene-one.tiff');/>
</div>
<div class="image-2">
<img source=url('../movie/scene-two.tiff');/>
</div>
<div class="image-3">
<img source=url('../movie/scene-three.tiff');/>
</div>
<div class="image-4">
<img source=url('../movie/scene-four.tiff');/>
</div>
<div class="image-5">
<img source=url('../movie/scene-five.tiff');/>
</div>
....etc.....
....etc.....
....etc.....
</div>
jQuery/Javascript could handle appending the sequential image classes instead of writting it all out by hand for each "frame".
CSS would look like:
#incredible-video img {
position:absolute;
width:100%;
height:auto;
background:cover;
}
But what would the jQuery/Javascript need to be to pull the off/can it be done? It would need to happen right after window load, and run on an infinite loop. Ofcourse audio is not happening in this example, but say we don't need it. Say we just want our End User to have a visually appealing page, with a minimal design implemented in the UI.
I love video animation, and really love sites built with Full Screen Backgrounds. But a site out with this visual setup and keeping it responsive is proving to strenuous a challenge. HTML5 will only get you so far, and makes mobile compatibility null and void (data usage protection). .GIF files are MASSIVE compared to calling in a .mp4, .Webm, or .OGG so that option is out.
I've actually recently played around with Adobe Edge Animate. Using the Edge Hero .js library I was able to reproduce a similar project to this: http://www.edgehero.com/tutorials/starwars-crawl-tutorial
I found it worked on ALL devices. Very cool. Made me think that maybe it's possibly to use this program or hit jQuery/Javascript directly to achieve the desired effect.
Thanks for taking a look at this one guys.
-Cheers,
Branden Dane
I found a viable solution to what I was looking to do. It's actually rather interesting. The answer it's introduces many interesting ideas on how we can display any kind of content dynamically on a site, in an app, or even a a full fledged software application.
The answer came about while diving hard into WebGl, canvas animation (both 2d and 3d), 2D video games techniques, and 3D video game techniques. Instead of looking for that "perfect" workflow, if you are someone interested in creating visually effective design and really seeing what the bleeding edge can do for your thoughts on development, skip the GUI's. Ignore the ads with software promising to make things doable in 5 min. It's not. However we are getting there. 3 major events we have to look forward too in just a few months are
1.) the universal agreement to implment WebGL natively in Opera, Chrome and Firefox (ofcourse), Safari will move to ship with webGL enabled, compered to the user having to enable it manually, and even IE is going to try and give her a go (in IE 12).
2.) Unity 3D, an industry standard in game development, has announced that next month it will release version 5, and with it a complete, intuitive workflow from start to exporting in Javascript (not JSON actual JavaScript). The Three.JS library more specifically as it is one of the most popular of the seemingly endless games engines out today.
How does this answer my initial question?:
Though WebGL has been around for about 3 years now, we are only now starting to see it shine. It's far more than a simple video game engine. With ThreeJS We have a full working JavaScript library, capable of rendering in WebGL, to the Canvas, or EVEN with a few CSS3 magic. Can't use your great movie as a mobile background? It ruining the overall UI? Cheer up. ThreeJS can working with both 2D and 3D javascript draw function, though not at the same time. Hover other libraries exist that allow you to bypass this rule.
AND DRUM ROLL. It is, or can be very easily made in a responsive or adaptive way.
The answer to my question came from looking at custom preloaders. Realizing I can create incredible looping animations in AE, and export them as GIFs offered the quality I wanted, but not control, no optimization, now sound. However, PNG Sequences CAN be exported. Then the epiphany hit. Before I just say what I am using to solve my problem, I'd like to leave a list of material anyone looking to move beyond easy development and challenge limits can use as a reference guide. This will be in order with what I began to where I am now. I hope it helps someone. The time to find it all out would be very much worth it.
1.) WebGL-Three.JS
WebGL opened my eyes to a new world. It's a technology quickly evolving and is here to stay. In a nutshell, all live applications you create now have access to more than just a CPU, but also the Graphics card as well. With GPU's getting more and more powerful, and not so unreasonably priced, the possibilities are endless. The idea we could be playing Crysis 3 "in-browser" without the need of a 3rd party client is no fiction. It's the future. Apply that to websites. Mind blown.
2.) First Cinema4D, then start working around with Verold.com & PlayCanvas.com
C4D is just my personal favorite because if it's easy integration with AE. You will find that with exporting your 3D models, Textures, Mesh's, anything to Three.JS (or any game engine period) that it is Blender that is the most widely supported. As of writing this, their are 2 separate C4D workflows to ThreeJS. Both are tedious, not always going to work, and actually just unnecessary. PlayCanvas was also a bit of a let down. Verold, however is an EXCELLENT browser based 3D editor in which you can import a variety of files (even FBX with Baked animations!) and when you are satisfied you can export into a standalone client or an iframe. The standalone client is superb. It is a bit glitchy, so have patience. You shouldn't get comfortable with it any way. Go back to your roots.
3.) iPhone app development, Android app dev (to an impressive extent), Web Sites, Web Apps, and more all function in a way that an application need only be made using JavaScript, HTML/5 and CSS/3. Once this is understood, and the truth hits you as to how much control you may not have known you had, then the day becomes good indeed. Learn the code. With a million untested and horrible "GUI's" out there that claim to do what you want, avoid the useless search. Learn the code. You can never go wrong at that point.
4.)What code do I need to learn?
JavaScript is the most essential. More on that in a moment. Seriously dive into creating apps of any kind with ThreeJS. Mr. Doob (co-creator of the library) has an EXCELLENT, well-documented website with tons of examples, tuts, and source code for you to dive into. Chrome Experiments is your next awesome option to see how people are really taking this kind of development to a new level. In the process of learning ThreeJS, you'll become more proficient with JavaScript. You will also start to play with things you maybe never had to, like JSON, or XML files for packaging data. You'll also learn how simple it is to implement Three.JS as a WebGL render, or even fallbacks to Canvas and even CSS3D if and when possible.
Before going on, I will make a caveat. I believe that once Unity 3D drops ThreeJS fro pro and free users, we will see much much more 3D in the web. In that case, it can't hurt to Download the software and play around a bit. It also serves an an excellent visual editor. There are exporters from Unity 3D to ThreeJS, but again they are still pre alpha stage.
2D or not 2D. that is the question
After getting a little dirty with 3D I moved into drawing in the 2D realm using the canvas. Flash still seems like a viable tool, but again, it's all about the code. Learn how to do it and you may find Flash is actually costing you time. I found 2D more difficult than 3D because the nature of 2D has yet to radically change, at least in my lifetime. You'll need to start learning Spritesheet creation tutorials. Nothing incredible hard if you know where to look. Use A photoshop, or an equivalent application. Create as many "movement" frames that if were put together in a GIF would be enough to seamlessly loop the sprite. OR render a master image out and cut around the elements naturally distinct pats. Ex: You want to make the guy you have standing on a street corner you created, stays. Cut that character up in as many separate PNG files as you believe you need. The second method is all about using the same sprite sheet we brought in the first try. The first scenario meant writing CSS selector and have javascript written for the regular user would become increasingly difficult.
First solution: Using CSS and Javascript to plot "frames" meticulously put together in the sprite sheet. This really can become a pain if not done correctly all the way through.
Second solution: We lose the frame by frame effect if we need it, but our overall 2D animations will look incredible. Also, building in this way creates more efficient games when implementing physics engines and setting up collision detectors. We will still use the same sprite sheet, however we only need to choose the frames we really actually need. The idea is to use dynamic tweening between frames that are called together via Javascript. In the end you have a fully animated Sprite, but could have done so with just one frame. Ex: You have a Stickman you want to show walking in a straight line. Solution one would jump frame by frame, creating a mild chop, to illustrate an animated walk. In solution 2, we take the Stick man and chop his dynamic bits apart so we can call them through JavaScript, then build our sprite from JavaScript directly. To create the walking effect, we cut apart stickmans legs and have those separate in the sprite sheet from the rest of his body (unless you need to animate another body part as well). We map out where the coordinates are for each piece of stickman. Free software like DarkFunctionEditor is one of many programs that will instantly take care of generating for you a reliable sprite sheet, printing out the coordinates of your sprite sheet after you bake it. With this knowledge, head into JavaScript and call in your variables that you wish to associate to the pieces of Stick Man and their corresponding coordinates. Then use Javascript to "build" all the pieces together. The walking animation is accomplished by the Tween we talked about earlier. Each leg essentially runs on a beautifully fluid path you set in JavaScript. No chop. Very easy to customize and control. If you want to make it even easier for yourself, try using one of the many libraries for Sprite animation. My favorite at the moment being CreateJS.
If you are looking to include collision detection or create particle systems then you will need a physics engine. For 2D I am torn between 2 at the moment. Right now I would put PhysicsJS over KineticJS. Both are fantastic. I believe PhysicsJS integrates with CaccoonJS and other mobile scripts easier.
My last words of advice are=, after reading this, understand you will be working will JavaScript. You will have a bit of jQuery to make it easy, but you will encounter things that are difficult on the way. My HUGE recommendation is to move into learning how to build using NodeJS. It's an Asynchronous Javascript Server-side and client-side development space. The documentation is wonderful. Your first stop should be learing about npm, and bower. Then understand how to effectively implement Grunt into the workflow. Try out NodeJS assets like Yeoman to give you "boilerplate" Node setups from which to start with. After you start understanding NodeJS mechanics and feel comfortable with setting up your initial package.json, you'll find that all this JavaScript will almost feel like it's writing itself after a certain point.
And that's all you need to know to get into 2D and 3D design and development. My initial question could have been answered using say a 3D rendered fullscreen. However my final conclusion came in a different method entirely.
After learning about 2D sprites and framing, then noticing the encoding process of gifs. I had the idea to try and create PNG Sprite Animations. Not PNG Gifs, per say. But rather creating a 2D scene and using a PNG sequence that I would then animate via JavaScript. I found a few great libraries on Github, both for my idea and cool ideas for GIF manipulation.
My final choices was with the Github Repo "jquery.animateSprite" Instead of mulling through sprite sheets, you take your individual PNG's and this library gives you an incredible amount of control in how you can store variables for later use, but also the animations you can pull off in general. For a full screen, responsive background that works on any device (and can even be animated to sound....) I'd recommend this technique. It works much like a flip book animation works, except much much more effectively.
I hope this helps someone along the way. If you have a question on anything I have mentioned here, or know of an area that needs further detail, then by all means please let me know.
-Cheers

What's the best solution for rendering a javascript game in Browser (complete viewport)

I think there are two diffrent solutions for the problem:
1) First the solution shown by aves Engine, which renders the whole game with html elements and external stylesheets e.g. CSS3 transfomations. Pro's are that the event-handling is much easier when working with div's than by rendering on canvas.
2) Like isogenicengine.com shows you could render the game on html5 canvas element. Mabye that's the better solution, because rendering on canvas is the way that millions of 2D-games were written before and in future the industry will optimize the drawing methods e.g. with hardware acceleration. At the moment the contra is that rendering on canvas is slow if you would like to render in fullscreen. If you would like to render only in a specific area of 200x200px that's okay, but in fullscreen you get stuck with a framerate of 10fps.
What do you think is the better way to create a game for the web?
Thanks for your opinion!
PS: If you have some articles about the topic please paste some links
I don't think it's a clear one size fits all kind of thing. I really think it depends on what you want to do with your game.
If you are doing a lot of vector graphic manipulation, perhaps canvas is a better choice vs engine like aves. For tiled based, maybe aves will work better.
You can render fast on fullscreen canvas if you're clever about only re-rendering dirty regions. But if your whole canvas needs to change every frame this obviously isn't going to help much.
I've spent alot of time recently looking into this issue and my conclusion is pretty simple.
Use HTML Elements, lets say that HTML5 actually makes progress and in one year the major browser support it. How long does it then take to get the general user base of the web on the latest browser (IE6 still has a choke hold in some sectors). So making the game available to as many people as possible is key! (In my mind anyways)
If however, your looking to learn and develop, go with canvas.

animated board game for web - not Flash - what is possible?

What is the best cross-browser way to get a flat mouse coordinate input data and simple callback for mouse events for my rectangular game area on my web page, even when it has loads of larger and smaller images and text string overlaid haphazard onto it?
And what is the best way to insert or remove a text string or semi-transparent image overlay at an arbitrary location (and Z order, specified relative to existing objects) in a board game rectangle with cross-browser DHTML?
And how can I stop the user selecting part or all of my montage of images (I just want them to interact with it as if it was Flash), and can I stop the right click menus coming up in IE, FF etc?
I want to do this without Flash because I want something that will work both on desktops and on iPhone and potentially other mobile platforms too.
I appreciate there are serious limitations (eg less image scaling capabilities, not vector, no rotation capability) to what I can do if I'm not using Flash but I'm very interested to know what capabilities are available.
Are there perhaps any frameworks available to make it easier than coding from scratch?
Would J/Query be a good match for some of the requirements? What else do I need?
I would recommend Google Web Toolkit. It lets you program in Java, which gives you all the type-safety and nice IDE functionality that Java entails, but compiles to Javascript so that you can just run it in a browser. It also does a ton of optimization and supports tons of features.
jQuery is excellent at doing this. I used jQuery's UI and Ajax functionality to implement the frontend for a game of chess.
I made it a little easier by creating an 8-by-8 table with unique div names for each tile, so Javascript can access them by getting the elements by id. If you can't create something like that, you do have the option of placing elements anywhere on the page (either absolute or relative to a given element). You can also easily change the z-index, including when the use is dragging a piece or when they have dropped it.
As far as disable right click and item selection goes, that's something that I didn't figure out how to do. You might want to take a look at some other Ajax games like Grand Strategy, which are much more polished than my experiment and may have figured out how to do this.
There are two main APIs for working with arbitrary drawing and positioning on the web, Canvas and SVG.
Take a look at Chrome Canvas Experiments and the Raphael Javascript toolkit to see some examples and Javascript abstractions.
The key is element.style.position = 'absolute'. To illustrate just what's possible here's how far I've managed to push javascript (and from scratch at that!):
http://slebetman.110mb.com/tank3.html - RTS in DOM! Click on units/squads then click somewhere else to tell them where to go. You can control both sides.

Recording and storing high-res hand drawing

Are there any advanced solutions for capturing a hand drawing (from a tablet, touch screen or iPad like device) on a web site in JavaScript, and storing it on server side?
Essentially, this would be a simple mouse drawing canvas with the specialty that its resolution (i.e. the number of mouse movements it catches per second) needs to be very high, otherwise round lines in the drawing will become "polygonal" when moving the pen / mouse fast:
(if this weren't the case, the inputDraw solution suggested by #Gregory would be 100% perfect.)
It would also have to have a high level of graphical quality, i.e. antialias the penstroke. Nothing fancy here but a MS Paint style, 1x1 Pixel stroke won't cut it.
I find this a very interesting thing in general, seeing as Tablet PCs are becoming at least a bit more common. (Not that they get the attention I feel they deserve).
Any suggestions are highly appreciated. I would prefer an Open Source solution, but I am also open to proprietary solutions like ActiveX controls or Java Applets.
FF4, Chrome support is a must; Opera, IE8/9 support is desired.
Please note that most "canvas" libraries around, and most answers to other questions similar to mine, refer to programmatically drawing onto a canvas. This is not what I am looking for. I am looking for something that records the actual pen or mouse movements of the user drawing on a certain area.
Starting a bounty out of curiosity whether anything has changed during the time since this question was asked.
I doubt you'll get anything higher resolution than the "onmousemove" event gives you, without writing an efficient assembler program on some embedded system custom built for the purpose. You run inside an OS, you play by the OS's rules, which means you're limited by the frequency of the timeslices an OS will give you. (usually about 100 per second, fluxuating depending on load) I've not used a tablet that can overcome the "polygon" problem, and I've used some high end tablets. Photoshop overcomes the problem with cubic interpolation.
That is, unless, you have a very special tablet that will capture many movement events and queue them up to some internal buffer, and send a whole packet of coordinates at a time when it dispatches data to the OS. I've looked at tablet api's though, and they only give one set of coordinates at a time, so if this is going to happen, you'll need custom hardware, and a custom driver, and custom apis that can handle packets of multiple coordinates.
Or you could just use a damned canvas tag, the onmousemove event, event.pageX|pageY some cubic interpolation, the "toDataURI" api of canvas, post the result to your php script, and then just say you did all that other fancy stuff.
onmousemove, in my tests, will give you one event per pixel of movement, limited only by the speed of the event loop in the browser. You'll get sparse data points (polygons) with fast movement and that's as good as it gets without a huge research grant and a hardware designer. Deal.
there are some applets for this in the oekaki world: Shi painter, Chibipaint or PaintBBS. Here you have php classes for integration.
Drawings produced by these applets can have quite good quality. If you register in oekakicentral.com you can see all the galleries and some drawings have an animation link that shows how was it drawn (it depends on the applet), so you can compare the possibilities of the applets. Some of them are open source.
Edit: See also this made in HTML 5.
Have a look at <InputDraw/>: a flash component that turns freehand drawing into SVG. Then you could send back the generated SVG to your server.
It's free for non commercial use. According to their site, commercial use price is 29€. It's not open source though.
IMHO it's worth a look.
Alternatively, you implement something based on svg-edit which is open source and uses jQuery (demo). If requires the Google Frame Plugin for IE6+ support though.
EDIT: I just found the svg-freehand-signature project (demo) that captures your handwritten signature and sends it to a server as a SVG using POST. It's distributed as a straight-forward and self-contained zip (works out of the box with Safari and Firefox, you may want to combine it with svgweb that brings SVG support to Internet Explorer).
EDIT: I successfully combined Cesar Oliveira's canvaslol (just look at the source of the page to see how it works) with ExplorerCanvas to have something on IE. You can also have a look at Anne van Kesteren's Paintr experiment.
markup.io is doing that with an algorithm applied after the mouseup.
I asked a similar question recently, and got interesting but not satisfying answers: Is there any way to accelerate the mousemove event?

What would be quicker Flash or Javascript?

I have an idea for a website which involves a canvas area which has no limit to its size. Basically you would be able to add items to the canvas (notes, photos whatever really). You would then be able to drag the canvas which would move those items along with the canvas until they disappear of screen. If you dragged the canvas back the other way they would appear again.
Question:
Which would be the best suited to this type of thing, Flash or Javacsript?
My main worries are the speed at which javascript/ flash could handle moving multiple items around on screen in the way discribed. Which language would handle better for a user on a slow machine.
UPDATE:
Thanks for your opnions guys, but to clarify what are the benefits of canvas over straight jQuery DOM manipulation? or visa versa. I've never used canvas before.
I don't think this is a question that will get you an objective answer - Flash developers will tell you Flash is better, web developers will say JavaScript. Trying to remain objective, I'd say that both technologies are suitable for what you describe, but have different advantages.
Flash will definitely render faster, even on slow machines, and is much richer graphically.
JavaScript is more accessible and works on a greater number of devices. Use a good JS framework though.
My initial thought would be to go with Javascript - if it's good enough for Google Maps, it's probably good enough for your app too.
Do you need to use canvas, what you're describing could be done with just javascript and the DOM. It would perform perfectly well unless there are a huge number of elements and it would be cross-browser compatible. For canvas you would require exCanvas to support IE which can sometimes slow things down.
The best way would surely be Javascript. And I would even say that you should reconsider the use of canvas. It sounds like it could be done in pure DHTML. In that way you wouldn't lose support for IE.
Consider using one of the javascript frameworks; Prototype or jQuery come to mind. It will ease your coding immensely. Given the development in javascript-engine performance (next versions of Webkit (Squirrelfish Extreme) and Mozilla (TraceMonkey) will be lightning fast) the worries about performance may be moot.
Also if you decide that you can't do it without canvas consider using John Resig's processing.js.
I'd say go with flash (or DOM if you don't need the extra punch). Here's my reasoning:
You can do cool transformations with canvas (skewing, rotations, gradient fade-ins in images, reflection effects, etc) that you can't with DOM. The downside is that doing these cool things is math heavy.
Canvas doesn't work in IE. IE's equivalent (VML) apparently has a root-access security hole.
The DOM has been around for longer than canvas and since it's more widely used (and depended upon), it's more optimized and polished than canvas.
The Flash community has a lot of good free components available that may already do what exactly you want.
Flash and DOM have a lot of good documentation and tutorials, canvas not so much.
Flash can do pretty much everything that the DOM and canvas can, plus audio, video and grabbing input from your web cam.

Categories

Resources