Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert multiple canvases to dataURL in html5

I want to join multiple canvases to make a single image. So is there any method to covert more than one canvases to toDataURL to make a single image?

like image 808
Muhammad Usman Avatar asked Jun 07 '12 09:06

Muhammad Usman


People also ask

Can you have multiple canvases HTML?

A webpage may contain multiple canvas elements. Each canvas may have an id using which you may target a specific canvas through JavaScript. Each canvas element has a 2D Context. This again has objects, properties, and methods.

What is canvas toDataURL ()?

The toDataURL() function returns a data: URL representing the canvas at the time that the function is called. Using this function you can transfer the canvas to your server (using jQuery for example) as a base64 encoded string and then use server-side scripting (eg PHP, ASP) to decode the string and save it to a file.

How do I get canvas toDataURL?

Here is the code to do that: var canvas = document. getElementById("ex1"); var dataUrl = canvas. toDataURL(); window.

How do I get an image URL from Canva?

To get the image data URL of the canvas, we can use the toDataURL() method of the canvas object which converts the canvas drawing into a 64 bit encoded PNG URL. If you'd like for the image data URL to be in the jpeg format, you can pass image/jpeg as the first argument in the toDataURL() method.


2 Answers

create a function that takes multiple arguments (canvas elements), puts them on one blank canvas, then returns the dataurl for the newly made canvas.

var getImadeData = function () {
    var i = arguments.length,
        tempCanvas = document.createElement("canvas"),
        ctx = tempCanvas.getContext("2d");
     while (i--) {
        ctx.drawImage(arguments[i], 0, 0);
    };
    return tempCanvas.toDataURL();
};

Now just feed the function multiple canvas elements you want to put into one dataurl like so.

var newData = getImageData(canvas1, canvas2, canvas3);

In this example, the last canvas is placed on the blank canvas first so make sure to order your canvas elements appropriately.

like image 69
r11 Avatar answered Oct 01 '22 16:10

r11


Yes, the drawImage method on the canvas 2d rendering context accepts canvas elements as image elements. So all you have to do is:

  • Create a new canvas
  • Get its context
  • Draw all other canvases to it with drawImage
  • Extract the final image from this new canvas
like image 41
bennedich Avatar answered Oct 01 '22 16:10

bennedich