Smoothing Free drawing in Html5 canvas - html

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'

Related

Detect coordinates within a shape

Theres 2 parts to my problem and they are related. I have a weird shape on my interface illustrated below, I am trying to randomly spawn MovieClips within its' boundaries but I am having some trouble finding a good way to do it.
Question 1: I can run an If condition to check with bitMapData.hitTest to see if the MovieClip has randomly spawn within this shape, if it doesn't simply retry with a new set of random coordinates. However, is there a better way? Like a way to only take into account coordinates within the shape? There will be plenty of MC spawned at one go so I am hoping to lessen the load, or at least find an efficient way to do this calculation.
Question 2: The MovieClips spawned within this shape will eventually have collision detection mechanics that will repel itself when interacted with. Is there a way to contain them within this shape via some kind of boundary detection?
If it was a square, we could easily have contained them with a quick check on all 4 edges, but not with this shape. Currently I am thinking of using bitMapData.hitTest again to detect for out-of-bounds after being repelled, but how do I know which Point() is the nearest 'edge' of this shape to return the MC to?
For question 1: I'm going to go on an assumption that you have some geometry data about the shape.
One method you can use to check if a point is within a shape is to take that point, then draw a line from that point to infinity (the edge of the screen) in one direction. Then count how many times that line intersects an edge of the shape. If it's odd, the point is within the shape (or on the edge) and if it's even, than that point is outside of the shape.
First link in google: https://www.geeksforgeeks.org/how-to-check-if-a-given-point-lies-inside-a-polygon/
Or can also try a more simple method (at the cost of doing more work): if the above shape is generated with all squares and rectangles and you know the point and size of all of those: can just do a check for the point vs all the squares and rectangles that make up the shape.
For question 2: As Organis mentioned, I'd go with a library like Box2D to do this. You'll most likely spend tons of time (that you may not want to) if you try to implement this alone.
The big issue is how much cpu or gpu the code uses. You're trying to avoid using any collision detection. Collision detection is having code do calculations to determine the edges of an object. It should be the last option.
Most of the time you know there's no need for collision detection. You know where everything is and how big it is. Everything has a centerpoint and comparing simple number coordinates is the lightweight way to check if there's a need to check further.
When things get near each other, you only need to do a collision detection on the immediate area around an object. See how your shape fits in a box that is easy to check for collisions? That box should get a collision check before the actual jagged shape inside it.
Yes that collision detection box has to be drawn or mapped but it's done when the object is defined, not when the game is playing. If you are using sprite sheets, keep an xml of the boxes or circles around the shapes.

Animating a path between two objects on HTML5 canvas

We're developing a game with impactjs that allows 'chaining' of entities as they are clicked. Basically this just draws a line between the two points, with a neon glow effect. So far, so good. Now, we have a request to make the 'chain' connections animated - fire, sparkles, etc. Essentially things that seem like they'd need actual graphic animations to look right. As the entities can be any distance/angle from each other, we're stuck at how to best implement a solution for this - that is, how to draw a diagonal image, for example, between two random points that we can animate. Any thoughts our suggestions on how to pull this off would be much appreciated.
Maybe create a particle entity with an Animation Sheet containing the necessary animations/particle effects. And then draw these particles along the line that from point A to point B.
When you want to animate it to fire/sparkles etc. run the animation for all those entities. in that line.
I'd be inclined to agree with Prat. Particle effects would most likely be what you need.
Here is a tutorial on generating particle effects in impact.js that might help you out.
http://www.pointofimpactjs.com/snippets/view/24/particle-effects-generation

html5 basic paint tool

I'm new to html5. And I'm trying to create a basic painting tool.
What I want to do in this tool is to have one or more shapes(maybe overlapping) and to paint the shapes without getting the colors overlapped. If a circle is drawn inside a rectangle and if I start coloring the circle, the rectangle should not be painted even if the mouse is dragged over it unless the dragging starts inside it.
To achieve this should I use multiple canvases or shapes?
Thanks in advance.
Well, first you need to program in the idea of keeping track of separate shapes. If you haven't already done that see here for a tutorial.
I imagine your shapes will all be kept as images or in-memory canvases themselves. I'm not sure how else you can do it.
There are a million ways you could do this, here's one:
When you start your drawing operation you need to detect which shape you're on. Then you draw that shape to an in-memory canvas and switch that temporary canvas' globalcompositeoperation to source-atop. This will make sure the paint can only paint in the already opaque regions of that shape (if that's your intent here, which it seems to be).
All while you are painting you will want to update the temporary canvas and redraw the main canvas constantly. While you are redrawing the main canvas, instead of painting that shape's image file you'll want to paint the temporary canvas (if you use canvases to keep the shapes you can just update those in real time).
If you are not using temporary canvases for each shape, when you stop the drawing operation you are gonna have to update the image associated with the shape to complete the operation.
Using an in-memory canvas (not added to the DOM) for every shape (that is the size of the shape and no larger) will make coding things slightly easier and might not be that bad on performance. I'd give it a try with 100 and 1000 (or more) in-memory canvases on your targeted platforms to see though.
The alternative is to use one in-memory canvas and have an HTMLImageElement (png) that represents every shape, but using the canvas.toImageURL function can be a bit of a performance hit in itself. I'd try both methods to see which works best in your case. If the shape count is small enough, it probably doesn't matter which.

Is it encouraged, or even beneficial to use Flash/HTML Canvas optimization when drawing shapes

I am starting to get a grasp of the HTML canvas and I wanted to know if it is encouraged to use optimization techniques. In games for example, is it encouraged to use bounding boxes and only redraw the portion of the screen that needs redrawing, or do people just blindly redraw everything. I ask this b/c I am creating a new engine for canvas and imposing bounding boxes complicates things greatly (ie. the user no longer has the freedom to quickly draw things to the stage).
Absolutely, it's almost always better to draw only what has changed on the screen at any one time. Attempting to draw everything causes unnecessary rasterisation of the images being drawn into one output image, when it's not even going to change on the screen.
In a small game I made a year ago, I was drawing a 2D array of tiles on the screen and getting around 15 frames per second. When I changed it to draw only the tiles visible on the screen, it was an amazing improvement. It will improve in this circumstance too.

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.