HTML5 canvas: Toggle between color/grayscale image - javascript

I've got an HTML5 canvas element in which a user can dynamically move, resize, and rotate a color photo.
I'd like the user to be able to toggle between grayscale and color.
I can think of two approaches, but neither is ideal:
1) Re-render the color image as grayscale (using a pixel-by-pixel loop) on every resize and rotate event (which could be several times a second)
2) Create a grayscale version server-side, and apply any canvas transformations to both images, but show only one of them at a time, depending on the toggle selection.
Can anyone think of a better solution than these two -- or, if no better solution exists, take a guess about which of the two would be the better choice?
Update: I implemented the method suggested below by Phrogz.

Create a second canvas (you don't even have to append it to the document) and use drawImage() to copy the color image onto it, and then (once) use getImageData()/putImageData() to make it greyscale.
Use this canvas as the source for future calls to drawImage() when you need the greyscale version, otherwise use the original image.
You are transforming the context, e.g. context.translate() / context.rotate() / context.scale(), to draw the image easily, right? There is no reason to keep rotating or resizing the source image as the user is transforming it.

You can also draw both images to two canvases (or a big one). That canvas probably doesn't even have to be added to the page, it can just be the element.
Then you draw the proper image from that canvas to the main canvas using the build-in methods. This will both be fast and not require server-side code.
You could even do the conversion to grayscale in a webworker, but that depends on if your clients do support it.

Related

Layering The Canvas Without Multiple Canvases

There I am creating a stamp maker in HTML,Jquery and javascript. In the editor of my application image is adding to HTML canvas (simple) and also the text, I just create new line element and then append it to the canvas.But the problem is that I want my image to be in back of text. I googled it alot and also search stackoverflow I got the solution of creating multiple canvases but in last I have to download the canvas to file for user. There is the problem. And I want to export whole canvas along with text one and second image together.If I create seperate canvas for the text and another for image and give image one low zindex it would be fine but there will be one canvas to be exported as image.
Link to multiple layers in canvas html5 - canvas element - Multiple layers
I am hopping that we would come up with an idea of how to download both canvases as an image or find a method to take image to back of the canvas.
Any answer would be appreciated.
If you store the text, second image and first image in variables, you could just draw them on the canvas in the order you prefer. This means that, whenever there's some change in the image or text, you should clean the canvas and redraw everything.
Also, you may be interested in Compositing, since it allows you to decide where a new object is drawn in relation to the existing drawing (on top, behind, etc.)

HTML5 SVG vs Canvas for big number of lines?

Question:
Is canvas more suitable than svg in the following case?
Case:
I'm drawing a chart (using d3js library) similar to this one (but with much more data):
http://mbostock.github.com/d3/talk/20111116/iris-parallel.html
It's based on an svg and it works fine for several thousands of lines (up to 5000), adding more lines (svg path) decreases the performance dramatically (scrolling in the page becomes slow)
Keep in mind: That I need to add mouse events (which is handy in svg)
Generally svg is better suited for vector images, like in your example. However canvas has a lot of benefits in modern browsers such as hardware acceleration, so for drawing the lines, as long as zooming, panning ect. isn't required performance will be using canvas.
Mouse events can be a pain using canvas, since you have to manually keep track of everything, so with 5000+ points using canvas it wont be fun. The trade off however will be once the points are drawn, assuming you only draw them once the page will behave fine regardless of the number of lines, since they are all drawn to a raster image and aren't part of the DOM.
Honestly though the best way to find it is to test what you currently have using canvas.
When performance becomes a problem, switching to canvas might be an option. In this case you can draw the canvas once. Afterwards it's pretty much treated like an image. Drawing might take some time, but afterwards it can be scaled pretty quickly. Note that it is possible to draw a rendered SVG to a canvas using the context.drawImage method (example). So you could keep your SVG generation code to create an SVG in the background, and then draw it to the canvas.
But keep in mind that it won't scale as beautiful as an SVG as soon as it is on the canvas. When the user zooms in, it will get blurry or pixely, depending on how the browser scales graphics.
Click events on canvas can be handled in two ways. Either keep an array of click targets, and add an onclick event handler to the canvas. When a click occurs, iterate the array and check which one is closest to the click coordinates.
The other option is to use hit regions. These have to be defined as polygonal paths.
+1 to everything said above. I've seen some amazing performance increases when using canvas over SVG and over compositing images using the DOM.
About manipulating the canvas image with mouse events, I imagine the best approach for an image such as you are describing is to abstract it away using a library like the following:
http://paperjs.org
http://kineticjs.com
http://www.createjs.com/#!/EaselJS
Keep your code away from the canvas itself and let a library do the thinking for you.

How to increase the canvas bit depth to create a higher quality picture in javaScript? and how to increate the canvas size when outputting

I'm new to HTML5 and JavaScript, and I'm trying to use the canvas element to create a high(ish) quality output image.
The current purpose is to allow users to all their own images (jpeg, png, svg). this works like a charm. however when I render the image it's always a 32-bit png. how can I create a higher quality picture using JavaScript(preferably) ?
when I output the file, it always seems to keep the same resolution as the canvas, how can I change this using JavaScript(preferably)
Thanks in Advance guys, I looked around for a while but I couldn't find the answer to this :(
If you want to create a larger image with getImageData or toDataURL then you have to:
Create an in-memory canvas that is larger than your normal canvas
Redraw your entire scene onto your in-memory canvas. You will probably want to call ctx.scale(theScale, theScale) on your in-memory context in order to scale your images, but this heavily depends on how they were created in the first place (images? Canvas paths?)
Call getImageData or toDataURL on the in-memory canvas and not your
normal canvas
By in-memory canvas I mean:
var inMem = document.createElement('canvas');
// The larger size
inMem.width = blah;
inMem.height = blah;
Well firstly, when you draw the image to the canvas it's not a png quite yet, it's a simple raw bitmap where the canvas API works on as you call it's methods, then it's converted to a png in order for the browser to display it, and that's what you get when you use toDataURL. When using toDataURL you're able to choose which image format you want the output to be, I think jpeg and bmp are supported along with png. (Don't think of it as a png converted to another format, cause it's not)
And I don't know what exactly do you mean by higher quality by adding more bits to a pixel, you see 32 bits are enough for all RGBA channels to have a true color 8 bits depth giving you way more colors than the human eye can see at once. I know depending on the lighting and angle in which the user is exposed to your picture his perception of the colors may vary but not the quality of it which I'd say only depends on the resolution it has. Anyway the canvas was not designed to work with those deeper colors and honestly that much color information isn't even necessary on any kind of scene you could render on the canvas, that's only relevant for high definition movies and games made by big studios, also, even if you could use deep colors on the canvas it would really depend on the support of the user's videocard and screen which I think the majority of people doesn't have.
If you wish to add information not directly concerned to the color of each pixel but maybe on potencial transformations they could have you better create your own type capable of carrying the imageData acceptable by the canvas API, keeping it's 32-bit format, and the additional information on a corresponding array.
And yes, the output image has the same resolution as the canvas do but there are a couple of ways provided for you to resize your final composition. Just do as Simon Sarris said, create an offscreen canvas which resolution is the final resolution you want your image to be, then, you can either:
Resize the raster image by calling drawImage while providing the toDataURL generated image making use of the resizing parameters
Redraw your scene there, as Simon said, which will reduce quality loss if your composition contains shapes created through the canvas API and not only image files put together
In case you know the final resolution you want it to be beforehand then just set the width and height of the canvas to it, but the CSS width and height can be set differently in order for your canvas to fit in your webpage as you wish.

How to add and remove (multiple) image from canvas.?

I am new to canvas (HTML5) i have to design a paint application on canvas. There is a feature like dynamic addition of the selected image at canvas (on mouse-movements) and functionality to delete and drag that added image (Same for Text addition). Now my Question is how can we delete the images from the canvas (Note :There are no fixed no. of images added to the canvas.) Can you please suggest me the approach ??
An HTML5 Canvas is much like a real-world canvas. When you draw to the canvas the ink changes the canvas, blending with the other contents already there and forever changing them.
Ask Monet "How do you add a new person to your painting?" and he might say "you just paint them where you want them!" Similarly, you use drawImage() to 'paint' an image to your Canvas.
However, if you ask Monet "How do you remove a person from a painting?" and he would likely look at you funny and then respond "Quoi? You would have to either make a new painting, or else paint over top of the person!" Similarly, if you want to "remove" something from your canvas you either have to start over (clear the canvas and draw everything except that thing) or re-paint what was 'behind' your image on top of it.
Here is an example I made that shows one way that you can 'save' part of a canvas (by drawing it to another canvas) and then later drawing it back over something to 'erase' it.
However, I generally advise you not to use an HTML5 Canvas unless you know why you need it. You mention adding and removing items, and also detecting mouse movements. Using a retained-mode drawing system—like HTML or SVG—means that you actually add or remove or change items in an object representation, and it is up to someone else (the browser) to figure out how to best redraw them.
You may be best served by letting the "paint" portions of the user input be done on one or more canvases, and then compositing these canvases with other items (such as <div>s with text, or <img> for pictures, or vector-based SVG artwork).
You can make your own retained-mode system on type of canvas, or you can use someone else's library that does this. But instead I'd suggest that you consider whether this is the best and easiest way to accomplish your goals.

How to resize or remove one object from canvas using Javascript?

Is there any change to remove or resize selected object from Canvas without changing other design.
For example:- I drawn circles (just for help Circle1, circle2, circle3) .
circle1 will be bottom of other two circles. Now I want to remove circle2 or re-size. But it should not effect other circles.
And it there any change do this without using clear Canavas method.
It should work something like powerpoint design just draw and resize and delete.
I do not think that is possible, canvas is a bitmap object as far as I know and anything you draw on it updates the image.
If you like to use circle as an object you probably should look to SVG
Citation:
"once the rectangle is drawn, the fact that it was drawn is forgotten by the system. If its position were to be changed, the entire scene would need to be redrawn, including any objects that might have been covered by the rectangle."
You could try drawing the circles on separate canvases. In this case all you would have to do is to get rid of the Canvas element containing the circle itself.
Of course this means you'll have to do use some CSS trickery (namely z-index and absolute positioning)... It also incurs some overhead. This might be acceptable if you are dealing with an adequate amount of objects.
I agree with David about SVG. That might be a good option.
With Canvas you have to start setting up your own framework. I started a few simple tutorials on the subject, including resizing shapes.
In short, you're gonna have to start keeping track of each object you have drawn so you can re-draw them every time something moves.
One possibility is to use a canvas library like fabric.js, which allows you to draw and access canvas objects programmatically. Having canvas contents as a number of objects makes it easy to modify those objects dynamically, without affecting anything else; move, resize, delete, clone, change properties (color, opacity, etc.)

Categories

Resources