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

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.

Related

Should I replace all img elements with the canvas element?

I'm new to the canvas element of html5. I'm specifically wondering when you should put an existing img element inside of a canvas element.
What's the benefit or appropriate use of this?
I've been reading Dive into HTML 5 and didn't quite get what I was looking for in their concluding statement on the topic of canvas:
The simple answer is, for the same reason you might want to draw text
on a canvas. The canvas coordinates diagram included text, lines, and
shapes; the text-on-a-canvas was just one part of a larger work. A
more complex diagram could easily use drawImage() to include icons,
sprites, or other graphics.
An image tag is best used for a static piece of imagery.
Canvas is, to quote the HTML5 working group, "a resolution-dependent bitmap canvas which can be used for rendering graphs, game graphics, or other visual images on the fly."
So, you can slap an image onto a canvas, but that is probably to augment some other piece of work you're creating, like a chart or a game graphic.
UPDATE AFTER YOUR UPDATE
So, if you want to create a really complex chart that tracks stock performance in real-time, you could use the canvas to draw the various bars of the graph, and then also use drawImage() to place company logos on the canvas to indicate which bar belonged to which bar.
Where img does the job, use that. canvas is a very powerful tool indeed, but:
While it's supported by a large portion of browsers today, img is still much more widely supported.
If you need to cater to users with JavaScript disabled, canvas cannot be used; canvas needs JavaScript to operate, whereas img doesn't.
That said, if you need something that only canvas can do, feel free. For example:
Do you need to load an image and then let users warp it or draw on it? A canvas would do quite nicely there.
Do you need to dynamically draw some charts and graphs? canvas would work well there, too.
When you have no need for the more advanced capabilities of canvas, though, and just need to display images, img is the most obvious and compatible choice.

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.

Zooming in and out on canvas

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.

HTML5 globalCompositeOperation vs clip

I have a large source image and I want to display a small section of it inside a circle, with leaving the part of the canvas outside of the circle transparent.
The Mozilla guide to Compositing with HTML5 covers two topics: globalCompositeOperation and clip. It looks like both of these will let me do what I want, so I'm wondering what the drawbacks are of each, and which I should use.
I could set globalCompositeOperation to source-atop (or source-in, but that seems buggy in WebKit). Then have the destination canvas be transparent with a black circle, and simply draw the source image over that. This will ensure that only the circle part will be filled in.
Or, I could draw a circular path and use clip to define a clipping region, then draw the source image over that, which should also ensure only the circle part will be filled in (in fact, Mozilla's page above even has an example of doing pretty much that with stars).
Will both of these techniques work as I say they will, or am I missing something?
If so, are there any major gotchas with either of these techniques which makes one clearly better than the other?
If not, which one has better performance in general?
I would (purely speculatively) imagine the globalCompositeOperation would have better performance, since it is applying the operation on a per-pixel level, whereas the clip operation needs to do polygon intersection. But that's just a hunch.
As of March, globalCompositeOperation did not work the same on all browsers.
Clip does... except the anti-aliasing, actually, which is sadly different per browser.
In my opinion the appropriate thing to do here is use clip. Using source-atop may work for your very specific situation, but it isn't very extensible as you described it. If you ever want to change any of it, like say have a background behind your circle, you'll run into trouble if you do it the globalComposite way.
And the tests are in: Clip is faster in every browser I tested, and massively faster in Firefox. See the results or try for yourself here

How canvas tag is beneficial in HTML5?

I am a junior developer I can't understand how canvas tag is beneficial for us?
I read lot of articles on that but I can't get the root benefit getting from the canvas tag.
Think of the difference between canvas and svg as the difference betwee Photoshop and Illustrator (or Gimp and Inkscape for you OSS folks). One deals with bitmaps and the other vector art.
With canvas, since you are drawing in bitmap, you can smudge, blur, burn, dodge your images easily. But since it's bitmap you can't easily draw a line and then decide to reposition the line. You need to delete the old line and then draw a new line.
With svg, since you are drawing vectors, you can easily move, scale, rotate, reposition, flip your drawings. But since it's vectors you can't easily blur the edges according to line thickness or seamlessly meld a red circle into a blue square. You need to simulate blurring by drawing intermediate polygons between objects.
Sometimes their use case overlaps. Like a lot of people use canvas to do simple line drawings and keep track of the objects as data structures in javascript. But really, they both serve different purposes. If you try to implement general purpose vector drawing in pure javascript on top of canvas I doubt you'd be faster than using svg which is most likely implemented in C.
Basically, thanks to canvas, we can now draw/render 2D shapes using HTML5 and the canvas API.
As an example of what's possible now with canvas, see this
Some possible uses for Canvas:
Image drawing program
Photo editing/manipulation
2D Games
Advanced image viewing such as Microsoft's Deep Zoom
If you can't understand how it's beneficial, then maybe it isn't from your point of view at least. Don't think that because it's there I have to use it somehow, pick and choose what technologies work for you based on what you're trying to build, an Accounting web app probably wouldn't need a canvas for instance.
The canvas will enable you to draw pixel perfect graphics.
The cool projects that came to mind for me are:
Visualize gps data. GPS data is just an XML list of coordinates. You could easily build something in canvas to "connect the dots".
An mobile app where the user can actual sign a document with her finger - canvas allows you to export out the rendered canvas drawing to PNG where it can be saved on the server.
In a game where you have avatars, you can allow the user to actual draw on the avatar. Moustaches anyone?
Other stuff:
In iOS / Android using lots of CSS3
effects like box-shadow can lead to
poor performance, especially when
animating. You can do a lot of these
graphics in a single canvas tag,
here's an example:
http://everytimezone.com/. This thing is flawless on an ipad.
Cool background effects. For example try going to Paul Irish's
site and move your cursor around the
background: http://paulirish.com/
In this HTML5 book sponsored by Google a lot of the effects are using
canvas:
http://www.20thingsilearned.com/ -
particularly the "page flip"
animations.
my personal take on canvas (and when I actually found a use case for canvas) is the ability to color pick and color change per pixel in a canvas element - actually moving the image from something we don't have any information about what is happening inside it to an element like all other DOM elements (and yes, I know about the current problems with canvas and DOM - sure this would be taken care of in the future)
sure - canvas made some sort of animation easier and pluginless, but that we could do before (mostly with flash) - I think the real importance is the ability to know what is happening on the page.