How to export (only) canvas as an image?

by darrion.kuhn , in category: Javascript , 4 months ago

How to export (only) canvas as an image?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , 4 months ago

@darrion.kuhn 

To export only the canvas as an image in JavaScript, you can use the built-in toDataURL() method of the <canvas> element. Here's an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// Get the canvas element
var canvas = document.getElementById('myCanvas');

// Get the data URL of the canvas
var dataURL = canvas.toDataURL("image/png");

// Create a new image element
var img = new Image();

// Set the src attribute of the image element to the data URL
img.src = dataURL;

// Create a new window to display the image
var win = window.open();
win.document.write('<img src="' + img.src + '" />');


In the above code snippet, replace 'myCanvas' with the ID of your canvas element. This code will create a new image with the contents of the canvas and display it in a new window. You can also save the data URL to a file or use it in any other way you like.