An old quesition, how to determine a point in a irregular shape? - javascript

i'm learning Html5 Canvas for some weeks, but the problem above baffle me a long time.
An irregular shape, possible is a circle, Rect, ellipse, polygon , or a path which constructed by some lines and bezier curve...
I found some algorithm for some shape, like circle, rect, and polygon,but , if i used them in canvas, it will be so complex for those many many shape.
I also view some canvas libary,such as Kinetic.js, paper.js, fabric.js,etc, they all do this work well, but the code of they is so much and blend here to there, so I can't get main point...
but i found,all of them don't use the 'isPointInPath' method to do this work. why? if use this, I can do this work too!
kinetic.js , i knew him use the getImageData to determine, but strange, the imagedata its got is no alpha(alpha is always 255), but the shape its drew is semitransparent, oh no my brain is out of thought.
so i'm here want to know how determine a point is in a irregular shape(possibly it's semitransparent) in canvas, even a think way can help me.
and , is some preblem with the 'isPointInPath' method? thus no one use it?

I see no reason why you can't use the built-in functions:
var isInPath = context.isPointInPath(x, y)
For strokes you can use - strokes are separate as a path can be an open line or you can have stroke widths that expands outside the actual polygon:
var isInStroke = context.isPointInStroke(x, y)
Note that this will only work for the last path (after using beginPath()). If you need to iterate several paths (ie. shapes) you need to re-construct the paths (no need to stroke or fill though). This is perhaps a reason why some don't use it.
Transparency is not an issue as checking paths involves the vectors, not the rendered output of those (color information is not part of the check).
In the future you will be able to use the Path object directly. Currently this is not implemented in any browser which otherwise would make iterating a breeze; so re-constructing last path is the only way for now. As you don't actually have to draw anything when checking, the performance is acceptable unless there are a zillion objects to iterate.

Related

HTML Canvas: mouse click hit test by using ghost canvas - anti-aliasing troubles

I'm writing an JavaScript application that is drawing arbitrarily shaped objects on a HTML canvas. The user should be able to select any of the objects by clicking on them.
To make this an O(1) operation I'm using a shadow canvas, i.e. a not displayed canvas that has exactly the same size, where each object drawn on the normal canvas is also drawn there - but with a color that represents it's ID.
So a simple ghostContex.getImageData() together with the mouse click coordinates gives me the color at that pixel and thus the ID of the clicked object.
All of that is working fine - except when I click on the exact border of an object.
As it's drawn with anti-aliasing on the ghost canvas I get a wrong color (as that color is a mixture between the correct ID and the ID of the object under it that was drawn before...). This wrong color is representing a wrong ID and thus I'm selecting a totally different object :(
How can I solve that problem?
Note #1: I'm already using the translate(0.5, 0.5) trick to prevent most anti-aliasing
Note #2: I was trying to write this application with SVG before, but especially this object selection was extremely slow as I guess it's been too many objects for the collision detection. That's the main reason why I want a O(1) approach now... Oh, and this way I can easily draw a much bigger line on the ghost canvas than the line is drawn on the normal canvas to make picking much easier.
Note #3: Relevant browsers are Firefox, Chrome, Android 2.3+ native and iOS native
The reason why I couldn't accept any answer here is quite easy and quite sad: it doesn't exist... :(
The antialiasing can not be switched of, the standard has no method for that. But the standard does have a hit test function (http://www.w3.org/html/wg/drafts/2dcontext/html5_canvas_CR/#hit-regions) that would do exactly what is needed here. Even in a nice way that would hide the nasty details for the developer - but it's not implemented in any of the browsers right now.
And implementation was looking to be far away till impossible (see e.g. comment #6 at https://code.google.com/p/chromium/issues/detail?id=328961). But apparently it gained momentum during the last month...
So what can be done in the mean time? What did I do?
In my code I could implement for each shape a isPointInShape() method. So I use the ghost canvas trick to get a shape and verify with the isPointInShape() that I really selected the correct shape. This helps in the anti aliased pixels not to pick a wrong shape (just think of clicking on the border of shape #2 where we had a 50% antialias transparency - this would tell you wrongly a selection of shape #1...).
If implementing a generic isPointInShape() is quite hard for your shape you could try a trick that I was reading of somewhere else (I didn't try it tough, so I haven't tested it...):
Create an additional ghost canvas of size 1x1 pixel that is positioned exactly on the mouse position. Then draw the shape of interest - when the A of the RGBA is changed, this shape does belong to that pixel.
I know this is an old post, but recently I had a similar issue. The way I solved the "seam of two colors" problem was doing a 10x10 pixel sampling of the secondary canvas instead of a single pixel. I then stringified the RGB values and used these as keys in a map that mapped to the object that color represents. So initially with the 1 pixel sampling I used the map immediately to determine the associated object but antialiasing created halfway colors that didn't exist in the map. The 10x10 method solves this problem by looping through the 100 RGB values returned and creating a "counting map." This map uses the stringified colors and maps them to a count, but only includes valid colors from the first map in the count. So you end up with a map saying you counted 65 red pixels and 23 blue pixels (where the remaining 12 pixels were some weird anti-alias hybrid). In the same loop where I was counting the colors I also maintained a variable for current max count and current color associated with that max count (to avoid looping through this new map again). Now at the end you have the color that was counted the most in that 10x10 sampling and can use that to map back to the object associated with it. You will only get an undefined result if no valid colors were found in the 10x10 sample which you can reasonably assume means the "background" was clicked.
I made up the name ghost context! Are you using my old tutorial? :)
In that old tutorial I do not clear the ghost context after each object is drawn to it. In your case, to fix your issue, you may need to clear after testing each object on the ghost context.
Make sure of course that you are translating the ghost context and normal context by precisely the same amounts. (and translating them back, or resetting the transformation, afterwards).

How can I draw a "transparent stroke" with Raphael.js

I am attempting to draw the path of a graph so that the path is transparent and the rest of the canvas is not. This way I can use the canvas as a mask and fill the path with different colors using html elements. Kind of like this:
There's no way to achieve this natively through Raphael, but it could be accomplished by some selective modification of the SVG produced by Raphael. Consider the use of a mask applied to the path. This technique is used to absolutely delicious visual effect here.
Don't forget that you can access the DOM node associated with a Raphael paper object through that paper object's canvas property (I don't know why Baranovskiy chose such a misleading name!). You could use this to interact directly with the SVG in the DOM, though I can't vouch for interactions between Raphael and custom modifications =)
To fill only the outer part of a path, you will have to draw what is often called a "donut" made of two path strings.
You will find a good example here : How to achieve 'donut holes' with paths in Raphael .
The idea is:
* give the outer path string as a large counter clockwise closed rectangle, telling the browser that what has to be filled is what is inside
* concat the inner path string as the clockwise closed path you want, telling the browser what has to be filled is what is outside.
Thus resulting in a filled shape with a hole which is the intersection of both filled shapes.

Javascript & Canvas: Endless random animation of slightly morphing circle?

I'm completely new to canvas and animating objects with it. I did a little bit of research (e.g. I found RaphaelJS) however I couldn't find any general answer or tutorial on how to create a "morphing" circle.
The image I posted here is what I would like to do:
I'd like to create one circle that is endlessly animated via a randomizer and is slightly morphing its contours.
I know this might be not a "real" question for this forum, however I just wonder if anyone could provide a few tipps or tricks on how to do something like that.
By "how to do something like that" I'm speaking actually about the technique on how to morph a circle. Do I have to "mathematically" create a circle with dozens of anchor-points along the edge that are influenced by a randomized function?
I would really appreciate some starting help with this.
Thank you in advance.
A circle can be reasonably well approximated by 4 cubic curves (one for each quarter and the control points on the tangents - google for the correct length of the control segments or calculate them yourself - see here. You could then randomly animate the control points within a small radius to get a wobbling effect.
Do I have to "mathematically" create a circle with dozens of anchor-points along the edge that are influenced by a randomized function?
Yes, you do, although it should not be necessary to create "dozens".
You may find the .bezierCurveTo() and .quadraticCurveTo() functions useful to provide smooth interpolated curves between control points.
When you can use a raster image then for every point you can displace it along the x-axis with a sin function. You can run the same function along the y-axis but instead to simply displace the pixel you can double it. This should give you a morphing circle but it also works with other shapes.

Canvas: When animating the drawing of a circle, how to avoid gaps between line segments?

I'm trying to animate a circle being drawn - here's a simplified version of what I'm doing:
http://jsfiddle.net/DQz37/1/
Problem is: I get slight lines / distortion between each line segment. Like this:
The constraints I'm dealing with are:
I need to render more than one circle on the same canvas, sometimes circles overlap
I need to render the circles using transparency / rgba coloring
I need to animate the rendering of the circles (so they look like they are being drawn)
Is this a common issue? How do you handle this kind of thing?
One easy way to fix this is to always be drawing one path, that way you guarantee that they will be connected well.
So instead of arcing from A to B and then B to C and then C to D, you arc from A to B, clear the canvas, arc from A to C, clear the canvas, arc from A to D, etc.
Here's a modified code bit as an example:
http://jsfiddle.net/ZV7rv/
Edit: In response to the comment, this is how to achieve the same thing while using a canvas buffer to keep the same state that was the canvas previously:
http://jsfiddle.net/7vVBC/
Basically, you want to compose two paths and join them perfectly without any seams, but that won't work, or if you are really lucky and it works in one browser, probably it's not going to work in another one. This is because the antialiasing algorithms are not implemented exactly the same, or might even be hardware accelerated and passed down to the videocard.
Hint: it's not possible to disable antialiasing.
As a programmer you keep stumbling into all kinds of issues that are not easy to do or convenient, and at that moment you need to step back a bit and reevaluate your choices. This is one of them.
Your only option in your specified constrains will be to redraw everything on each frame, or don't use alpha, and overlap segments a bit to make sure you don't have spaces because of antialiasing.

Raphael cumulative vs absolute scaling/rotation/translation?

I'm trying to draw an interactive map in Javascript, using Raphael to do the heavy lifting.
The map background is a fairly complicated thing containing a grid, the map elements, labels, etc. On top of this I'm then going to draw the stuff the user is actually working with. Because the background is complex, I don't want to have to rerender it every frame. So, after drawing it I would like to reuse those drawing elements, merely changing the translation, rotation, scaling of the background as the user pans, zooms, etc.
Unfortunately I'm rather confused by Raphael's transformation primitives: they're not behaving as I would expect. If I call scale(), the scaling appears to apply to the original size of the drawing element; but translate() is cumulative, so it applies to the previous translation. rotate() can be either, as it has an option I can set...
Is it possible to do absolute translation? That is, to be able to specify the absolute coordinates of the new center of my objects (which are usually paths)? Failing that, is keeping track of the old location so I can apply a delta when I want to move it to the new location a reasonable way of doing this?
Or would I be better off simply rerendering the whole thing every frame? (I see suggestions that Raphael isn't good at transformations of complex drawings, as most of it is done in Javascript; looking at the SVG that's being produced, I see that the translation appears to be getting backed into the path data, which would bear this out...)
(BTW, FWIW I'm using the GWT Raphael interface for all this.)
You can use Element.attr to set absolute positions. Just change x and y properties:
myElement.attr("x", myX);
myElement.attr("y", myY);
I've used the raphael-zpd plugin with success. I'm not sure if that will plug into GWT - you could check out their source code and adapt it to your use case.
Project: https://github.com/somnidea/raphael-zpd
Source: https://github.com/somnidea/raphael-zpd/blob/master/raphael-zpd.js

Categories

Resources