How to perform this animation using canvas? - javascript

I am creating rotating planets by projecting a 200x100 bitmap on a sphere. Since this projection
is costly for an animation, I hacked an array with value-pairs ["pixel address in sphere projection image", "what pixels of original bitmap goes to that address"].
To just transfer them quickly with no math.
I end up with 16008 values, which represent the 8004 pixels we need to draw a circle (representing a sphere), on
a 100x100 canvas - planets always have radius 50 and I scale them later.
Now, to rotate a planet, all I have to do is to "shift" the second item of the pair by 1 pixel for a very slow rotation, and
higher values for a the illusion of faster rotations. I end up with this bottleneck:
for (var i=0;i<16008;i+=2)
{
//the planet object has a canvas holding its texture, and
//the texturePixels array is the data of that texture after
//a getImageData() of that texture canvas. finalPixels is
//the pixel data for the final planet on screen projected image.
locationInTexture=valuePairs[i]+planet.angle;//angle increases by 4 cuz each pixel is 4 rgba values
locationInProjection=valuePairs[i+1];
finalPixels[locationInProjection]=planet.texturePixels[locationInTexture]
finalPixels[locationInProjection+1]=planet.texturePixels[locationInTexture+1]
finalPixels[locationInProjection+2]=planet.texturePixels[locationInTexture+2]
finalPixels[locationInProjection+3]=255; //alpha isnt relevant
}
I also made the variables global to accelerate things. But it is still slow. My problem might
be that I should minimize DOM access, but I am accessing the pixel data in 2 canvases thousands
of times, and my guess is these don't behave just like normal 'arrays', though I might
be wrong in this case of simple array items reading/writing. The alternative seems to be to do this:
1-at load, get texture pixel data in a normal array instead of the one inherited from the canvas (is this relevant?)
2-get final pixel arrangement to a new normal array, instead of to the final planet display canvas directly.
3-create an image from that last array data and drawImage on the planet display canvas, and done, assuming
the (create image+draw it on final canvas) would be faster.
Or maybe we can even create a canvas with the sphere directly from the normal array data? Or using images
would be cheaper than canvases? How do I do this? Help please.
Thanks in advance :)
P.S. A screen can have tens of planets+moons when showing a solar system. I decided to ask before embarking
on an "img instead of canvas" approach, and find later that that is not the problem.

Related

Making rectangular image an irregular shape on a canvas

After searching the web for just over an hour, I have not found any luck.
I am wondering if it is possible, if so how do I create a transparent image on a js canvas not to be considered as a rectangle, rather only the visible area of it.
For example if you click in a transparent spot on the png the script does not considered that part of the object.
Thank you :)
Yes, you can get info about every pixel on the canvas using context.getImageData
A Demo: http://jsfiddle.net/m1erickson/tMmzc/
This code will get an array containing info about every pixel on the canvas:
var data=ctx.getImageData(0,0,canvas.width,canvas.height).data;
The data array is organized with 4 sequential element representing the red,green,blue & alpha(opacity) information about one pixel.
The data array's elements #0-3 have the top-left pixel's r,g,b,a info.
The data array's elements #4-7 have the next rightward pixel's r,g,b,a info.
...and so on...
Therefore, given the mouse position on the canvas you can fetch that pixel's alpha info. If the alpha value is zero then that pixel is transparent.
This code will read the alpha value under the mouse and determine if it's transparent:
var isTransparent = data[(mouseY*canvas.width+mouseX)*4+3]>0;

HTML5 Remove previous drawn object in canvas

I have a polygon object (say a car) drawn inside a HTML5 canvas with help of methods moveTo and lineTo. I want to repeatedly draw that object at different positions in the canvas (simulating a moving object). My problem is that the previous drawn object is not getting cleared. Instead, multiple images are drawn on the canvas. How can I fix this issue?
You have to clear the canvas at the start of every draw frame
context.clearRect(0, 0, canvas.width, canvas.height);
Canvases are just arrays of pixels, they know nothing of the shapes you have drawn.
There are animation tricks that used to be used on bitmapped displays (e.g. "xor drawing") that can be used to remove the old shape before you draw the new one, but on modern machines it's generally far simpler (and perfectly fast) to just erase the canvas and start again for each frame.
Given your comments to other answers, I'd suggest just using two Canvases - one for the static background and one for the car. If the background image is static it could even be an <img> element instead of a Canvas.
If the car image is static you could also just draw that once, and then use CSS positioning to set its position relative to the background for each frame.
suppose your shape is car then you first have to assign a new graphic like:
car.graphics = new createjs.Graphics();
car.graphics
.setStrokeStyle(1)
.beginStroke("#000000")
.moveTo()
.lineTo()
.lineTo()

Why do images lose quality after the context has been rotated?

I'm making a top-down shooter game that relies on the avatar always being rotated pointing to the mouse cursor. I achieve rotation like this:
//Rendering.
context.save(); //Save the context state, we're about to change it a lot.
context.translate(position[0] + picture.width/2, position[1] + picture.height/2); //Translate the context to the center of the image.
context.rotate(phi); //Rotate the context by the object's phi.
context.drawImage(picture.image, -picture.width/2, -picture.height/2); //Draw the image at the appropriate position (center of the image = [0, 0]).
context.restore(); //Get the state back.
When the phi is zero, the image is rendered in its normal quality, with sharp edges and detectable pixels. But, when I set the phi to a nonzero value (actually, when it's not 0, Pi/2, Pi, Pi+Pi/2 or 2Pi), the image looses it's sharpness and the individual pixels can't be seen anymore, because they are blurred out.
Here's a screenshot (sorry about the general bad quality of the screenshot, but I think that the difference is more than noticeable):
This is, well, a bit unacceptable. I can't have the images always blurred out! Why is this happening and can I solve it?
You could try
context.imageSmoothingEnabled = false;
See docs:
context.imageSmoothingEnabled [ = value ]
Returns whether pattern fills and the drawImage() method will attempt to smooth images if they have to rescale them (as opposed to just rendering the images with "big pixels").
Can be set, to change whether images are smoothed (true) or not (false).
If you want a true pixel-art retro style effect, you'd need to manually create rotated sprite images for several angles, look up the appropriate sprite for the current value of phi, and draw it without rotation. This obviously requires a fair amount of art work!
IF you are rotating images around their center point, make sure the image itself has an even number of pixels. Once you end up on odd coordinates the image data needs to be interpolated for the target canvas. Apple has some nice documentation on translating and rotating the canvas.
So for any image, as suggested above use rounding to snap to full pixels.
context.translate(Math.floor(img.width/2), Math.floor(img.height/2));
This way every source pixel of your image will always be drawn exactly into a pixel inside the canvas and blurring does not occur. This however is only true for multiples of 90 degrees.
It seems that all browsers do, to some extend, antialiasing in image drawing so you will probably have to provide rotated images as sprites.
According to this Chromium bug report you might be lucky there if they haven't fixed it yet. Read through and you'll learn that Ian Hickson likely opposed making antialiased image drawing optional.
(picture.width/2, picture.height/2) point won't always work.
(Math.floor(picture.width/2) + 0.5, Math.floor(picture.height/2) + 0.5) should help.
Well, actually it is something you cannot get around
If you rotate an image by a multiple of 90 degrees, your library should smart enough so that no interpolation is applied.
But as soon as you rotate an image by an angle different from a multiple of 90 degrees, you need to interpolate. As a consequence, you get that smoothing. If you are interested in the theory, you may look for a book on computer graphics or image processing.
For the concrete case of image rotation you may have a look at this paper,
http://bigwww.epfl.ch/publications/unser9502.html

Three mouse detection techniques for HTML5 canvas, none adequate

I've built a canvas library for managing scenes of shapes for some work projects. Each shape is an object with a drawing method associated with it. During a refresh of the canvas, each shape on the stack is drawn. A shape may have typical mouse events bound which are all wrapped around the canvas' own DOM mouse events.
I found some techniques in the wild for detecting mouseover on individual shapes, each of which works but with some pretty serious caveats.
A cleared ghost canvas is used to draw an individual shape by itself. I then store a copy of the ghost canvas with getImageData(). As you can imagine, this takes up a LOT of memory when there are many points with mouse events bound (100 clickable shapes on a 960x800 canvas is ~300MB in memory).
To sidestep the memory issue, I began looping over the pixel data and storing only addresses to pixels with non-zero alpha. This worked well for reducing memory, but dramatically increased the CPU load. I only iterate on every 4th index (RGBA), and any pixel address with a non-zero alpha is stored as a hash key for fast lookups during mouse moves. It still overloads mobile browsers and Firefox on Linux for 10+ seconds.
I read about a technique where all shapes would be drawn to one ghost canvas using color to differentiate which shape owned each pixel. I was really happy with this idea, because it should theoretically be able to differentiatate between millions of shapes.
Unfortunately, this is broken by anti-aliasing, which cannot be disabled on most canvas implementations. Each fuzzy edge creates dozens of colors which might be safely ignored except that /they can blend/ with overlapping shape edges. The last thing I want to happen when someone crosses the mouse over a shape boundary is to fire semi-random mouseover events for unrelated shapes associated with colors that have emerged from the blending due to AA.
I know that this not a new problem for video game developers and there must be fast algorithms for this kind of thing. If anyone is aware of an algorithm that can resolve (realistically) hundreds of shapes without occupying the CPU for more than a few seconds or blowing up RAM consumption dramatically, I would be very grateful.
There are two other Stack Overflow topics on mouseover detection, both of which discuss this topic, but they go no further than the 3 methods I describe.
Detect mouseover of certain points within an HTML canvas? and
mouseover circle HTML5 canvas.
EDIT: 2011/10/21
I tested another method which is more dynamic and doesn't require storing anything, but it's crippled by a performance problem in Firefox. The method is basically to loop over the shapes and: 1) clear 1x1 pixel under mouse, 2) draw shape, 3) get 1x1 pixel under mouse. Surprisingly this works very well in Chrome and IE, but miserably under Firefox.
Apparently Chrome and IE are able to optimize if you only want a small pixel area, but Firefox doesn't appear to be optimizing at all based on the desired pixel area. Maybe internally it gets the entire canvas, then returns your pixel area.
Code and raw output here: http://pastebin.com/aW3xr2eB.
If I understand the question correctly, you want to detect when the mouse enters/leaves a shape on the canvas, correct?
If so, then you can use simple geometric calculations, which are MUCH simpler and faster than looping over pixel data. Your rendering algorithm already has a list of all visible shapes, so you know the position, dimension and type of each shape.
Assuming you have some kind of list of shapes, similar to what #Benjammmin' is describing, you can loop over the visible shapes and do point-inside-polygon checks:
// Track which shape is currently under the mouse cursor, and raise
// mouse enter/leave events
function trackHoverShape(mousePos) {
var shape;
for (var i = 0, len = visibleShapes.length; i < len; i++) {
shape = visibleShapes[i];
switch (shape.type ) {
case 'arc':
if (pointInCircle(mousePos, shape) &&
_currentHoverShape !== shape) {
raiseEvent(_currentHoverShape, 'mouseleave');
_currentHoverShape = shape;
raiseEvent(_currentHoverShape, 'mouseenter');
return;
}
break;
case 'rect':
if (pointInRect(mousePos, shape) &&
_currentHoverShape !== shape) {
raiseEvent(_currentHoverShape, 'mouseleave');
_currentHoverShape = shape;
raiseEvent(_currentHoverShape, 'mouseenter');
}
break;
}
}
}
function raiseEvent(shape, eventName) {
var handler = shape.events[eventName];
if (handler)
handler();
}
// Check if the distance between the point and the shape's
// center is greater than the circle's radius. (Pythagorean theroem)
function pointInCircle(point, shape) {
var distX = Math.abs(point.x - shape.center.x),
distY = Math.abs(point.y - shape.center.y),
dist = Math.sqrt(distX * distX + distY * distY);
return dist < shape.radius;
}
So, just call the trackHoverShape inside your canvas mousemove event and it will keep track of the shape currently under the mouse.
I hope this helps.
From comment:
Personally I would just switch to using SVG. It's more what it was
made for. However it may be worth looking at EaselJS
source. There's a method Stage.getObjectUnderPoint(), and their demo's
of this seem to work perfectly fine.
I ended up looking at the source, and the library utilises your first approach - separate hidden canvas for each object.
One idea that came to mind was attempting to create some kind of a content-aware algorithm to detect anti-aliased pixels and with what shapes they belong. I quickly dismissed this idea.
I do have one more theory, however. There doesn't seem to be a way around using ghost canvases, but maybe there is a way to generate them only when they're needed.
Please note the following idea is all theoretical and untested. It is possible I may have overlooked something that would mean this method would not work.
Along with drawing an object, store the method in which you drew that object. Then, using the method of drawing an object you can calculate a rough bounding box for that object. When clicking on the canvas, run a loop through all the objects you have on the canvas and extract ones which bounding boxes intercept with the point. For each of these extracted objects, draw them separately onto a ghost canvas using the method reference for that object. Determine if the mouse is positioned over a non-white pixel, clear the canvas, and repeat.
As an example, consider I have drawn two objects. I will store the methods for drawing the rectangle and circle in a readable manner.
circ = ['beginPath', ['arc', 75, 75, 10], 'closePath', 'fill']
rect = ['beginPath', ['rect', 150, 5, 30, 40], 'closePath', 'fill']
(You may want to minify the data saved, or use another syntax, such as the SVG syntax)
As I am drawing these circles for the first time, I will also keep note of the dimensional values and use them to determine a bounding box (Note: you will need to compensate for stroke widths).
circ = {left: 65, top: 65, right: 85, bottom: 85}
rect = {left: 150, top: 5, right: 180, bottom: 45}
A click event has occurred on the canvas. The mouse point is {x: 70, y: 80}
Looping through the two objects, we find that the mouse coordinates fall within the circle bounds. So we mark the circle object as a possible candidate for collision.
Analysing the circles drawing method, we can recreate it on a ghost canvas and then test if the mouse coordinates fall on a non-white pixel.
After determining if it does or does not, we can clear the ghost canvas to prepare for any more objects to be drawn on it.
As you can see this removes the need to store 960 x 800 x 100 pixels and only 960 x 800 x2 at most.
This idea would best be implemented as some kind of API for automatically handling the data storage (such as the method of drawing, dimensions...).

Detect mouseover of certain points within an HTML canvas?

I've built an analytical data visualization engine for Canvas and have been requested to add tooltip-like hover over data elements to display detailed metrics for the data point under the cursor.
For simple bar & Gaant charts, tree graphs and node maps with simple square areas or specific points of interest, I was able to implement this by overlaying absolutely-positioned DIVs with :hover attributes, but there are some more complicated visualizations such as pie charts and a traffic flow rendering which has hundreds of separate areas defined by bezeir curves.
Is is possible to somehow attach an overlay, or trigger an event when the user mouses over a specific closed path?
Each area for which hover needs to be specified is defined as follows:
context.beginPath();
context.moveTo(segmentRight, prevTop);
context.bezierCurveTo(segmentRight, prevTop, segmentLeft, thisTop, segmentLeft, thisTop);
context.lineTo(segmentLeft, thisBottom);
context.bezierCurveTo(segmentLeft, thisBottom, segmentRight, prevBottom, segmentRight, prevBottom);
/*
* ...define additional segments...
*/
// <dream> Ideally I would like to attach to events on each path:
context.setMouseover(function(){/*Show hover content*/});
// </dream>
context.closePath();
Binding to an object like this is almost trivial to implement in Flash or Silverlight, since but the current Canvas implementation has the advantage of directly using our existing Javascript API and integrating with other Ajax elements, we are hoping to avoid putting Flash into the mix.
Any ideas?
You could handle the mousemove event and get the x,y coordinates from the event. Then you'll probably have to iterate over all your paths to test if the point is over the path. I had a similar problem that might have some code you could use.
Looping over things in this way can be slow, especially on IE. One way you could potentially speed it up - and this is a hack, but it would be quite effective - would be to change the color that each path is drawn with so that it is not noticeable by humans but so that each path is drawn in a different color. Have a table to look up colors to paths and just look up the color of the pixel under the mouse.
Shadow Canvas
The best method I have seen elsewhere for mouseover detection is to repeat the part of your drawing that you want to detect onto a hidden, cleared canvas. Then store the ImageData object. You can then check the ImageData array for the pixel of interest and return true if the alpha value is greater than 0.
// slow part
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillRect(100,100,canvas.width-100,canvas.height-100);
var pixels = ctx.getImageData(0,0,canvas.width,canvas.height).data;
// fast part
var idx = 4 * (mouse_x + mouse_y * canvas.width) + 3;
if (pixels[idx]) { // alpha > 0
...
}
Advantages
You can detect anything you want since you're just repeating the context methods. This works with PNG alpha, crazy compound shapes, text, etc.
If your image is fairly static, then you only need to do this one time per area of interest.
The "mask" is slow, but looking up the pixel is dirt cheap. So the "fast part" is great for mouseover detection.
Disadvantages
This is a memory hog. Each mask is W*H*4 values. If you have a small canvas area or few areas to mask, it's not that bad. Use chrome's task manager to monitor memory usage.
There is currently a known issue with getImageData in Chrome and Firefox. The results are not garbage collected right away if you nullify the variable, so if you do this too frequently, you will see memory rise rapidly. It does eventually get garbage collected and it shouldn't crash the browser, but it can be taxing on machines with small amounts of RAM.
A Hack to Save Memory
Rather than storing the whole ImageData array, we can just remember which pixels have alpha values. It saves a great deal of memory, but adds a loop to the mask process.
var mask = {};
var len = pixels.length;
for (var i=3;i<len;i+=4) if ( pixels[i] ) mask[i] = 1;
// this works the same way as the other method
var idx = 4 * (mouse_x + mouse_y * canvas.width) + 3;
if (mask[idx]) {
...
}
This could be done using the method ctx.isPointInPath, but it is not implemented in ExCanvas for IE.
But another solution would be to use HTML maps, like I did for this little library : http://phenxdesign.net/projects/phenx-web/graphics/example.htm you can get inspiration from it, but it is still a little buggy.
I needed to do detect mouse clicks for a grid of squares (like cells of an excel spreadsheet). To speed it up, I divided the grid into regions recursively halving until a small number of cells remained, for example for a 100x100 grid, the first 4 regions could be the 50x50 grids comprising the four quadrants.
Then these could be divided into another 4 each (hence giving 16 regions of 25x25 each).
This requires a small number of comparisons and finally the 25x25 grid could be tested for each cell (625 comparisons in this example).
There is a book by Eric Rowell named "HTML5 CANVAS COOKBOOK". In that book there is a chapter named "Interacting with the Canvas: Attaching Event Listeners to Shapes and Regions". mousedown, mouseup, mouseover, mouseout, mousemove, touchstart, touchend and touchmove events can be implemented. I highly suggest you read that.
This can't be done (well, at least not that easily), because objects you draw on the canvas (paths) are not represented as the same objects in the canvas. What I mean is that it is just a simple 2D context and once you drawn something on it, it completely forgets how it was drawn. It is just a set of pixels for it.
In order to watch mouseover and the likes for it, you need some kind of vector graphics canvas, that is SVG or implement your own on top of existing (which is what Sam Hasler suggested)
I would suggest overlaying an image map with proper coordinates set on the areas to match your canvas-drawn items. This way, you get tooltips AND a whole lot of other DOM/Browser functionality for free.

Categories

Resources