Zooming in and out on canvas - html

I wrote a paint application using the HTML5 canvas element.
Now I want to give the user an option to zoom in and out while painting.
How can I do this?

There are a few ways. It really depends on what you're looking for.
You could do it by scaling the entire context, as in ctx.scale(2,2), and then redrawing everything at this larger scale. Several things drawn, like paths and text, will scale gracefully. To accomplish this you will need to keep good track of everything drawn so far.
Another way is to take the entire canvas and draw it back to itself. This requires a temporary canvas because the operation is really: Draw to temp canvas, clear main, draw back to main scaled.
Another way is to use CSS transforms to merely zoom the canvas itself, which will make the image blurry (its zoomed!) but does not require changing any of the pixels already on the canvas.

Related

Correct way to fill shape with image cropped from sprite

I am slightly confused about the "correct" way in KineticJS to fill a shape with partial images (crops) from a combined image file (sprite).
Seems like one can either use fillPatternImage with a defined offset, which seems to draw the complete image, albeit with the rest of the image invisible. I only got acceptable performance after I moved those shapes to an extra layer as my sprite is relatively large and the impact of not cropping correctly decreased the fps dramatically.
All alternatives that I have found use the attribute "fill" with another attribute "image" in it, but this seems to result in black background every time.
Using an Image-shape would help, but is rarely usable since my shapes are seldom rectangular.
Since the KineticJS-documentation does not mention specifying crop coordinates ("just" offset, w/o width and height), what is the absolute correct way to do it?
The absolute "absolute correct way" would depend on the platform and your particular code, but.
Have you looked at sprites? http://www.html5canvastutorials.com/kineticjs/html5-canvas-kineticjs-sprite-tutorial/.
To mask simple animated sprites I'd use this in adition of plain javascript after each draw.
context.globalCompositeOperation = 'destination-in';
The performance of drawImage with composite operations is better than drawing shapes manually on webkit, at least.

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.

How to undraw, hide, remove, or delete an image from an html canvas?

this.context.drawImage(myimage, 0, 0);
Putting the image on the canvas is pretty well covered all over the web.
But how do I remove it after it's there?
Canvas is an immediate drawing surface. This means that you execute a command on it (drawImage or fillRect) and it does that command, and it doesn't give a damn what has just done. There is no undoing of something.
You had a hard time searching for it because there's no such thing as "removing" for a Canvas. All it knows is that it has some pixels of some color from somewhere. It has no idea where.
To simplify a bit, there are generally two ways:
Clear the entire canvas, and draw everything all over again EXCEPT the one image you do not want drawn
Use two canvases, one that only has the image and one with all the other stuff. Clear this canvas with clearRect(0,0,width,height) and you're done.
You'll notice in 1. that you will probably have to start keeping track of the things that you draw on canvas if you want some of them selectively removed or repositioned. Instilling object persistence, or rather turning canvas from an immediate drawing surface to a retained drawing surface, is something that a lot of canvas libraries do. If you want to do it yourself, I've written a few tutorails to help people get started.
If you want to look into libraries, take a peek at easel.js. It's pretty learnable.
Option 1:
Draw a rectangle over it of the same color as the background.
Option 2 (works for non-trivial background, but slower):
Get the pixel data from the canvas before drawing the image, then redraw that pixel data to remove the image.
So I came up with a quick and easy way to clear my canvas. I just put my <canvas> tags in between <p> tags with an Id, then each time i needed my canvas cleared I just rerendered my <p> tags by changing the innerHTML, works like a charm.

html5 canvas shapes fill

I have a basic paint application on a canvas, and I want to make a drawing-border and by that create a stencil. In other words, I want to make a shape, and then I want the user to be able to draw only inside it, even when he tries to draw outside.
Do you have any idea how can i do it?
thanks
This can be achieved by making a clipping region. The basic idea is that there is a path on the canvas that all drawing is constrained to.
Make the shape, and instead of calling stroke() or fill(), call clip()
If you don't quite get how clipping regions work, there are a few examples around.

Clear Canvas Rect (but keep background)

I'm trying to animate a circle and just moving it horizontally which works fine. However while the circle is moving, I have to do a clearRect over that circle so that it redraws it self in the horizontal direction. When I do a clearRect it also makes the background have white box around so effectively its going to be one white horizontal line in the direction the circle is moving.
Is there a way to clear the circle without clearRect?
If I have to keep redrawing the background after clearRect the canvas will flicker when theres say 10 circles moving in that area.
Any other approaches to solving this?
function drawcircle() {
clear();
context.beginPath();
context.arc(X, Y, R, 0, 2*Math.PI, false);
context.moveTo(X,Y);
context.lineWidth = 0.3;
context.strokeStyle = "#999999";
context.stroke();
if (X > 200)
{
clearTimeout(t); //stop
}
else
{
//move in x dir
X += dX;
t = setTimeout(drawcircle, 50);
}
}
function clear() {
context.clearRect(X-R, Y-R, 2*R, 2*R);
}
Basics: HTML5 Canvas as a Non-Retained Drawing Mode Graphics API
First, let us discuss the manner in which the HTML5 Canvas works. Like a real-world canvas with fast-drying oil paints, when you stroke() or fill() or drawImage() onto your canvas the paint becomes part of the canvas. Although you drew a 'circle' and see it as such, the pixels of the circle completely replaced the background (or in the case of anti-aliasing at the edges of the circle, blended with and forever changed them). What would Monet say if you asked him to 'move' one of the people in a painting a little bit to the right? You can't move the circle, you can't erase the circle, you can't detect a mouseover of the circle…because there is no circle, there is just a single 2D array of pixels.
Some Options
If your background is fully static, set it as a background image to your canvas element via CSS. This will be displayed and overlaid with content you draw, but will not be cleared when you clear your canvas.
If you cannot do the above, then you might as well just clear the entire canvas and re-paint it every frame. In my tests, the work needed to clear and redraw just a portion of the canvas is not worth the effort unless redrawing the canvas is very expensive.
For example, see this test: http://phrogz.net/tmp/image_move_sprites_canvas.html
In Safari v5.0.4 I see 59.4fps if I clear and re-draw the entire canvas once per frame, and 56.8fps if I use 20 clearRect() calls and 20 drawImage() calls to re-draw just the dirtied part of the background each frame. In this case it's slower to be clever and keep track of small dirty regions.
As another alternative, use a retained-drawing graphics system like SVG or HTML. With these, each element is maintained independently. You can change the position of the item and it will magically move; it is up to the browser to intelligently draw the update in the most efficient manner possible.
You can do this while retaining the power of custom canvas drawing by creating and layering multiple canvases in the same HTML page (using CSS absolute positioning and z-index). As seen in this performance test, moving 20 sprites via CSS is significantly faster than trying to do it all yourself on a single canvas.
Flickering?
You wrote:
If I have to keep redrawing the background after clearRect the canvas will flicker when theres say 10 circles moving in that area.
That has never been my experience. Can you provide a small example showing this 'flicker' problem you claim will occur (please specify OS, browser, and version that you experience this on)? Here are two comments by prominent browser developers noting that neither Firefox nor Safari should ever show any flickering.
This is actually very easy to accomplish by simply positioning more than one canvas on top of each other. You can draw your background on a canvas that is (wait for it...) in the background, and draw your circles on a second canvas that is in the foreground. (i.e. stacked in front of the background canvas)
Multiple canvases is actually one of the best ways to increase performance of anything animation where elements of the final image move independently and do not not necessarily move in every frame. This allows you avoid redrawing items that have not moved in every frame. However, one thing to keep in mind is that changing the relative depth (think z-index) of items drawn on different canvases now requires that the actual <canvas> elements be reordered in the dom. In practice, this is rarely an issue for 2D games and animations.
Contrary to what the accepted answer suggests; yes, you can restore previous draw states, and contrary to what the other answers imply; no, you don't need additional canvases to do so:
The CanvasRenderingContext2D API includes the functions getImageData() and putImageData(). After creating a background image, store the whole thing in a variable const background = context.getImageData(x, y, width, height) (a simple RGBA bitmap of type Uint8ClampedArray), then after wiping the canvas with clearRect() or whatever, restore the background image simply by passing that variable back in the opposite direction: context.putImageData(x, y, background).
There are two ways you can do it that may reduce the flickering, esp if you have many circles.
One is double buffering, and for a brief question on this you can look at:
Does HTML5/Canvas Support Double Buffering?
Basically, you draw on two canvases, and swap them in and out as needed.
This would be the preferable option, esp with many changes per frame, but, the other way I have done this is to just draw over the circle I want to erase, using the background color, then draw with the correct color the new circle.
The only problem is that there is a small chance that you may leave some evidence of the attempted erasing, as it seems that for some shapes it is hard to get it to draw exactly on top.
UPDATE:
Based on a comment you can look at this discussion about double buffering on the canvas:
HTML canvas double buffering frame-rate issues
The basic idea is to keep track of everything you have drawn, with the current position, then on a separate canvas, you redraw everything, then, flip them out, and then I would just redraw again, in the new positions, to ensure that the image looks exactly like it should. Swapping them in and out is a quick operation, the only problem would be if you put event handlers on the canvas, in this case, have them on the div or span surrounding the canvas, so this information doesn't get lost.