Smooth canvas sketching without clearing (redraw) - html

I'm trying to find a way to smooth out the points for sketching to get a cleaner result. I've found this example, and the result looks quite good
I've found some ways that use cubic curves to smooth out the edginess, but all of them requires the line to be redrawn from the beginning since they work with multiple points.
My initial idea was to "draw" the final "part" of the line when there are enough points to calculate the bezier (simply 2 frames after points are taken) to overcome the need of "redrawing" every time.
Any ideas/workarounds about this will be appreciated.
Thanks!

Related

Moving an object in elliptical Path

In my LigGdx based game, I wish to move my Sprite in an elliptical path to reach the destination. I do not find any support in Universal tween engine. Sample of route example is shown below.
Questions :
Is there is any methods in UniversalTween Engine to have a elliptical path ?
Also let me know what is waypoints in UniversalTween Engine ?
Thanks in Advance !
The Universal Tween Engine now supports curves - Default is CatmullRom which would definitely be able to provide the smooth movement you want.
It's a little tricky to get your head around at first but not that bad once you get used to it.
Universal Tween Engine
Details of update that added curves
Well I have searched up this question for you and discovered you many people have already asked this question, and none of them got an answer, yet. So I will try to answer as best as I can. I believe that my method is not the best. But if your application is not time or performance sensitive, then this method may work.
Now this comes to a math problem. You know that the screen is make out of pixels and there is no point making it overly detailed because it isn't possible. So you can do this:
They grey line being your intended line, and the green line being your actual drawn line. If you move objects using the tween engine along the green path and switch path when hitting the red dots. You could mimic an elliptical movement. However, you need to use math and calculate your path. You could set the coordinates of your path as a constant for every screen size, or you could calculate it every time.
Overall, the more points you calculate, the more elliptical the movement will be.
Anyways if you look at this website, it teaches you how to tween.
You can use Tween.to(...); to help you tween to the points.
Hope this helped you

AS3 with Nape physics: How can I find a tangent from a point to a body?

The short question: Is there any simple way in Nape to calculate the points of tangency with a Nape body object or shape given a point outside that body?
What I'm trying to do is create Worms-style rope physics. It basically works as an extendable line/distance joint that automatically breaks into segments when it comes in contact with the level geometry. I do this by raycasting from the most recent pivot point; if there is a collision I offset from the collision point by a couple of pixels, create a new rope segment, and make that point the new pivot. In case my character is swinging around a sharp corner, I then recast from that point, looping as necessary, until I'm clear of the level geometry.
It works amazingly well given my lack of experience, but there's one little cosmetic glitch. The rope won't wrap "tightly" around a horn-shaped protrusion. It's pretty easy to see why this is happening. Refer to the figure below.
I cast a ray each time I step the Nape world at 60 frames/second. Figure 1 shows the difference between two example raycasts. The character (not pictured) is at the end of the line, and he's fallen past the cliff "edge" in relation to the pivot in one step, so the collision point falls short of the desired point of tangency.
Figure 2 is what I end up with. The wraparound logic still works, by offsetting from the surface and recasting, but it doesn't appear "taut."
What I want is something like Figure 3, which corrects the angle to find the actual point of tangency with the body and creates the new pivot from that.
My planned fallback is to offset the angle of the raycast by small increments and recast until I no longer strike the level geometry, then back up one and use that as the collision point. Even that will probably require fewer computations than "curving" around like in Figure 2, but I'm still wondering: is there an even simpler way?
Excuse me for not commenting, but I don't have needed points for that :)
I've used something similar before (not exactly the same) and I think the way to go is to save the points of each cast, get the one with highest difference from the starting point, based on the y axis (if the rope goes up, then you get the point with smallest y and vice versa (rope going down from starting point)).
Then you can fix the angle to point to this specific point, marked as an "edge". Later you can continue with the common pattern, as the rope will go in the other direction (exactly like the edge of a cliff).

HTML5 Canvas not preserving the draw order

I am trying to draw a rough outline of a building in canvas.
I'm achieving the effect below by creating a series of squares for each side, plus the top 'roof' and then drawing them in sequence basically following the Painter's algorithm.
The screenshot on the left is showing how it should look. This is painting each square separately.
To improve performance I want as few .stroke() and .fill() calls as possible so I queue up all the moveTo() and lineTo() calls and paint them all in one big go.
Tests have shown that (at least for lines) this gives a massive performance improvement and I've verified it myself.
Unfortunately as you can see from the right screenshot, when I paint the buildings only once at the end the layering basically gets destroyed. It paints things in a seemingly random order.
Is the canvas supposed to work this way? Why doesn't it draw everything in the order I told it to draw in like the first screenshot?
Does anyone know a good work around for this behaviour?
If you're sending it all the moveTos and lineTos etc as one big batch, it's going to draw them as if you were rendering one large shape (where you'd want to see all the inner strokes).
There's a minor performance penalty for running multiple draw operations, but it's usually not worth making your code harder to understand and debug.

Smoothing Free drawing in Html5 canvas

I am implementing free drawing with HTML5 canvas. Currently every thing is working fine. I am using moveTo() and lineTo() for every mousemove. I have to fine tune the drawing;
when I draw some curve like lines with rapid movements, the drawing will be drawn like joints of straight lines. Is there any alternative way for drawing, to make the drawing smoother?
I dont think there is a better way for the drawing itself, however, if you put the draw functions directly onto the mouse move event handlers, then that would slow it down,
To speed that up you could just save the coordinates in an array in the event handlers and wait for the mouse to stop moving before walking trough the array and drawing.
The advantage would be that the events are called more reapidly, making smoother curves, the disadvantge would be that there is a 'lag' if you move the mouse alot.
An alternative would be to try and detect when the user curves and use the appropiate curve drawing method.
I actually did the same thing:
ctx.beginPath();
ctx.moveTo(lp.x-.5, lp.y-.5); // Last recorded position.
ctx.lineTo(cp.x-.5, cp.y-.5); // Current position at time of call.
ctx.stroke();
Bezier Curves are great for pen-like (paths) functionality, but I've ended up with unintended results with that as well, namely the curve between P0 and P2 being too distant from P1... This can be handled by adding extra points against which to evaluate the function (taking it to higher degrees, which seems to be how adobe does it).
I've spent two days answering this question, doing a lot of research of the best examples, tearing through code where available. There are essentially two responses:
1.) Apply a filter – a box- or gaussian- blur will smooth the rough edges a little, making it look less angular.
2.) Apply a Bezier Curve – Between the mousedown and mouseup events, log an array of the points and apply the curve. The longer the line, the slower the re-rendering.(Muro - deviantArt's canvas app appears to do this). [NB: If the idea is to create an artistic web app for people to draw on, show them the original line until the smooth rendering is complete.]
I like somewhere in between, personally. A slight blur tends to soften things, especially near corners, and makes slowly placed (thus frequent, shorter lines) much softer).
Something I'll add, which may be completely obvious so I apologize: Make sure you've set your cap style to 'round' –– ctx.lineCap = 'round'

Converting Pixels to Bezier Curves in Actionscript 3

Ok, so I'll try to be as descriptive as possible.
I'm working on a project for a client that requires a jibjab-style masking feature of an uploaded image.
I would like to be able to generate a database-storable object that contains anchor/control positions of a bezier shape, so I can pull it out later and re-mask the object. This all is pretty easy to do, except for one catch : I need to create the bezier object from a user-drawn outline.
So far, here's how I imagine the process going:
on mouse down, create a new sprite, beginFill, and moveTo mouse position.
on mouse move, lineTo an XY coordinate.
on mouse up, endFill.
This all works just great. I could just store the info here, but I would be looking at a GIGANTIC object full of tons of pretty useless x/y coordinates, and no way to really make fine-tuning changes outside of putting handles on every pixel. (I may as well give the end user a pencil tool...)
Here's what I'm thinking as far as bezier curve calculation goes :
1: Figure out when I need to start a new curve, and track the xy of the pixel on this interval. I'm imagining this being just a pixel count, maybe just increment a count variable per mouse move and make a new one every x pixels. The issue here is some curves would be inaccurate, and others unnecessary, but I really just need a general area, not an exact representation, so it could work. I'd be happier with something a little smarter though.
2: take each new x/y, store it as an anchor, and figure out where a control would go to make the line curve between this and the last anchor. this is where I get really hung up. I'm sure someone has done this in flash, but no amount of googling can seem to help me out with the way to get this done. I've done a lot of sketching and what little math I can wrap my brain around, but can't seem to figure out a way of converting pixels to beziers.
Is this possible? All I really need is something that will get close to the same shape. I'm thinking about maybe only placing anchors when the angle of the next pixel is beyond 180 degrees in relation to the current line or something, and just grabbing the edge of the arc between these changes, but no matter how hard I try, I can't seem to figure out how to get this working!
Thanks for your help, I'll be sure to post my progress here as I go, I think this could be really useful in many applications, as long as it's actually feasible...
Jesse
It sounds like a lot of work to turn pixels into Bezier curves. You could try using something like the Linear least squares algorithm. http://en.wikipedia.org/wiki/Linear_least_squares
A different tact, could you have your users draw vector graphics instead? That way you can just store the shapes in the database.
Another cool method of converting raster to vector would be something like this iterative program: http://rogeralsing.com/2008/12/07/genetic-programming-evolution-of-mona-lisa/
Good luck
In my answer to this question I discuss using autotrace to convert bitmaps to beziers. I recommend passing your user drawing through this program on the server. Autotrace does a fantastic job of tracing and simplifying so there is no need to try and reinvent the wheel here.
Thanks for the answers, although I guess I probably should be more specific about the application, I'm really only needing an outline for a mask, so converting images to vectors or polygons, despite how cool that is, doesn't really fix my issue. The linear least squares algorithm is mega cool, I think this might be closer to what I'm looking for.
I have a basic workaround going right now, I'm just counting mouse moves, then every X (playing with it to get most desirable curve) moves, I grab the xy position. then, I take every other stored xy, and turn it into an anchor, the remaining xys are turned into controls. This is producing somewhat desirable results, but has some minor issues, in that the speed at which the mask is drawn effects the number of handles, and it's really just getting a general area, not a precise fit.
Interestingly, users seem to draw slower for more precise shapes, so this solution works a lot better than I had imagined, but it's not as nice as it could be. This will work for the client, so although there's no reason to pursue it further, I like learning new things, and will spend some off the clock time looking into linear least equations and seeing if I can drum up a class that will do these computations for me. If anyone runs across some AS3 code for this type of thing, or would like some of mine, let me know, this is an interesting puzzle.