Рубрики

canvas

Effortless objects to depict on a small canvas

There are so many objects that you can draw inspiration from. For example, the sky, flowers, birds, buildings, animals, and many more. The beauty of nature and our surroundings is a big inspiration for art as art is a representation of nature and the human soul. If you feel like you’re running out of inspiration or if you feel like your creative juices have stopped flowing, this article will provide you with different ideas of easy things to paint on a canvas.


Capture HTML canvas as GIF/JPG/PNG/PDF?

Is it possible to capture or print what’s displayed in an HTML canvas as an image or PDF? I’d like to generate an image via canvas and be able to generate a PNG from that image.

Follow
32.4k 25 25 gold badges 144 144 silver badges 173 173 bronze badges
asked May 29, 2009 at 0:28
Parand Parand
104k 48 48 gold badges 152 152 silver badges 186 186 bronze badges
May 23, 2016 at 16:20
Oct 8, 2016 at 22:10
Example here freakyjolly.com/…
Jun 8, 2018 at 9:45
You might find canvas2image library useful for this: github.com/hongru/canvas2image
Dec 29, 2018 at 1:17

If someone is looking for an answer related to React, I wrote two tutorials about it yesterday: React Component to Image and React Component to PDF.

Sep 30, 2021 at 15:35

[H1toH2]

16 Answers 16

Sorted by: Reset to default

Original answer was specific to a similar question. This has been revised:

const canvas = document.getElementById('mycanvas') const img = canvas.toDataURL('image/png') 

With the value in img you can write it out as a new image like so:

document.getElementById('existing-image-id').src = img 
document.write(''); 

Follow
32.4k 25 25 gold badges 144 144 silver badges 173 173 bronze badges
answered Aug 18, 2010 at 16:37
donohoe donohoe
13.9k 4 4 gold badges 38 38 silver badges 59 59 bronze badges
one more question, how can I save the image I got in this tag to server. Any guess??
Jun 27, 2011 at 8:41

But if i use var img = canvas.toDataURL(“image/jpeg”); am getting the background as complete black. How to rectify that

Dec 23, 2013 at 14:55
Oh come on. I answered this in 2009. What do you expect?
May 21, 2014 at 16:48
@donohoe actually you answered it in August 2010 🙂
May 21, 2015 at 21:59

It would use a lot less memory to do something like var img = new Image(); img.src = canvas.toDataURL(); document.body.appendChild(img); . The document.write code is making the data URL, them making a HTML string, then putting a copy of that string in the DOM, the browser then has to parse that HTML string, put another copy on the image element, then parse it again to turn the data URL into image data, then finally it can show the image. For a screen size image that’s a huge amount of memory/copying/parsing. Just a suggestion

Jan 25, 2017 at 8:26

HTML5 provides Canvas.toDataURL(mimetype) which is implemented in Opera, Firefox, and Safari 4 beta. There are a number of security restrictions, however (mostly to do with drawing content from another origin onto the canvas).

So you don’t need an additional library.

   

Theoretically this should create and then navigate to an image with a green square in the middle of it, but I haven’t tested.

Follow
2,181 5 5 gold badges 27 27 silver badges 42 42 bronze badges
answered May 29, 2009 at 2:48
olliej olliej
35.9k 9 9 gold badges 59 59 silver badges 55 55 bronze badges
Where the image will be saved. Location in my local?
Jul 17, 2013 at 3:30

the image will be displayed as an image in your browser. You can then save it to disk or whatever. Here’s a quick and dirty generic “Canvas2PNG” bookmarklet that converts the first canvas in the page to PNG and displays it in the browser in a new window: javascript:void(window.open().location = document.getElementsByTagName(“canvas”)[0].toDataURL(“image/png”))

Apr 2, 2014 at 12:10

If the image is a few MB in size, prepare to crash your browser (I did that a while back in FireFox).

Mar 14, 2015 at 14:16
How could this be modified to render multiple images?
Oct 15, 2015 at 11:56

Data URIs have max length, so there is upper limit on the size of an image that you can put to a data url.

Jun 14, 2018 at 4:24

I thought I’d extend the scope of this question a bit, with some useful tidbits on the matter.

In order to get the canvas as an image, you should do the following:

var canvas = document.getElementById("mycanvas"); var image = canvas.toDataURL("image/png"); 

You can use this to write the image to the page:

document.write(''); 

Where “image/png” is a mime type (png is the only one that must be supported). If you would like an array of the supported types you can do something along the lines of this:

var imageMimes = ['image/png', 'image/bmp', 'image/gif', 'image/jpeg', 'image/tiff']; //Extend as necessary var acceptedMimes = new Array(); for(i = 0; i < imageMimes.length; i++) < if(canvas.toDataURL(imageMimes[i]).search(imageMimes[i])>=0) < acceptedMimes[acceptedMimes.length] = imageMimes[i]; >> 

You only need to run this once per page – it should never change through a page’s lifecycle.

If you wish to make the user download the file as it is saved you can do the following:

var canvas = document.getElementById("mycanvas"); var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); //Convert image to 'octet-stream' (Just a download, really) window.location.href = image; 

If you’re using that with different mime types, be sure to change both instances of image/png, but not the image/octet-stream. It is also worth mentioning that if you use any cross-domain resources in rendering your canvas, you will encounter a security error when you try to use the toDataUrl method.

Follow
answered Jul 1, 2013 at 14:52
meiamsome meiamsome
2,896 1 1 gold badge 17 17 silver badges 19 19 bronze badges

With your solution for downloading the file, I must choose the software I want to use, it’s a bit unconvenient. Is there a way to re-replace the mime as png once downloaded?

Dec 18, 2013 at 9:51

@So4ne I don’t think so, it has to be an image/octet-stream to prompt the user for a download. If you get rid of that line, you’ll end up with the page redirecting to the image. I would love to know if someone else knows a way to do this nicely, though.

Dec 26, 2013 at 17:59
Sep 7, 2014 at 11:44

This is great. Thanks! But what if I want to save to server and not local? Will a form file input accept the img src as something that is uploadable?

Jun 29, 2015 at 21:26

Oops. Just found the answer. Leaving the previous question in case someone else is looking as well stackoverflow.com/questions/13198131/…

Jun 29, 2015 at 21:29

function exportCanvasAsPNG(id, fileName) < var canvasElement = document.getElementById(id); var MIME_TYPE = "image/png"; var imgURL = canvasElement.toDataURL(MIME_TYPE); var dlLink = document.createElement('a'); dlLink.download = fileName; dlLink.href = imgURL; dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':'); document.body.appendChild(dlLink); dlLink.click(); document.body.removeChild(dlLink); >

Follow
answered May 22, 2015 at 9:40
david.barkhuizen david.barkhuizen
5,289 4 4 gold badges 37 37 silver badges 38 38 bronze badges
The saved file stays in .svg format. How to save it as png?
Apr 4, 2016 at 7:16

This is a nice solution except that it may not work on IE. Getting error “The data area passed to a system call is too small”

Jul 10, 2017 at 3:40
In Chrome it says “Network error”, while in Firefox it works great. (On Linux)
Jan 5, 2018 at 12:55

I would use “wkhtmltopdf”. It just work great. It uses webkit engine (used in Chrome, Safari, etc.), and it is very easy to use:

wkhtmltopdf stackoverflow.com/questions/923885/ this_question.pdf 

Follow
2,181 5 5 gold badges 27 27 silver badges 42 42 bronze badges
answered Feb 2, 2011 at 2:33
lepe lepe
24.8k 9 9 gold badges 101 101 silver badges 108 108 bronze badges
I’m in the wkhtmltopdf camp, too. We’ve been using it for archiving and its AMAZING.
Mar 30, 2012 at 15:06

How to use WKHTMLtoPDF in page that required login info ? I am using Jsreport to convert to PDF but I capture my content with HTML2Canvas ,I have issue with sending the Canvas as parameter to JSreport

Jan 2, 2017 at 0:02
@khaledDehia check: stackoverflow.com/questions/10287386/…
Jan 2, 2017 at 2:30

Here is some help if you do the download through a server (this way you can name/convert/post-process/etc your file):

-Post data using toDataURL

-Set the headers

$filename = "test.jpg"; //or png header('Content-Description: File Transfer'); if($msie = !strstr(

Capture HTML canvas as GIF/JPG/PNG/PDF?

Is it possible to capture or print what's displayed in an HTML canvas as an image or PDF? I'd like to generate an image via canvas and be able to generate a PNG from that image.

Follow 32.4k 25 25 gold badges 144 144 silver badges 173 173 bronze badges asked May 29, 2009 at 0:28 Parand Parand 104k 48 48 gold badges 152 152 silver badges 186 186 bronze badges May 23, 2016 at 16:20 Oct 8, 2016 at 22:10 Example here freakyjolly.com/… Jun 8, 2018 at 9:45 You might find canvas2image library useful for this: github.com/hongru/canvas2image Dec 29, 2018 at 1:17

If someone is looking for an answer related to React, I wrote two tutorials about it yesterday: React Component to Image and React Component to PDF.

Sep 30, 2021 at 15:35 [H1toH2]

Example

100% javascript and no other 3-rd library.

  

Theoretically this should create and then navigate to an image with a green square in the middle of it, but I haven't tested.

Follow
2,181 5 5 gold badges 27 27 silver badges 42 42 bronze badges
answered May 29, 2009 at 2:48
olliej olliej
35.9k 9 9 gold badges 59 59 silver badges 55 55 bronze badges
Where the image will be saved. Location in my local?
Jul 17, 2013 at 3:30

the image will be displayed as an image in your browser. You can then save it to disk or whatever. Here's a quick and dirty generic "Canvas2PNG" bookmarklet that converts the first canvas in the page to PNG and displays it in the browser in a new window: javascript:void(window.open().location = document.getElementsByTagName("canvas")[0].toDataURL("image/png"))

Apr 2, 2014 at 12:10

If the image is a few MB in size, prepare to crash your browser (I did that a while back in FireFox).

Mar 14, 2015 at 14:16
How could this be modified to render multiple images?
Oct 15, 2015 at 11:56

Data URIs have max length, so there is upper limit on the size of an image that you can put to a data url.

Jun 14, 2018 at 4:24

I thought I'd extend the scope of this question a bit, with some useful tidbits on the matter.

In order to get the canvas as an image, you should do the following:

var canvas = document.getElementById("mycanvas"); var image = canvas.toDataURL("image/png"); 

You can use this to write the image to the page:

document.write(''); 

Where "image/png" is a mime type (png is the only one that must be supported). If you would like an array of the supported types you can do something along the lines of this:

var imageMimes = ['image/png', 'image/bmp', 'image/gif', 'image/jpeg', 'image/tiff']; //Extend as necessary var acceptedMimes = new Array(); for(i = 0; i < imageMimes.length; i++) < if(canvas.toDataURL(imageMimes[i]).search(imageMimes[i])>=0) < acceptedMimes[acceptedMimes.length] = imageMimes[i]; >> 

You only need to run this once per page - it should never change through a page's lifecycle.

If you wish to make the user download the file as it is saved you can do the following:

var canvas = document.getElementById("mycanvas"); var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); //Convert image to 'octet-stream' (Just a download, really) window.location.href = image; 

If you're using that with different mime types, be sure to change both instances of image/png, but not the image/octet-stream. It is also worth mentioning that if you use any cross-domain resources in rendering your canvas, you will encounter a security error when you try to use the toDataUrl method.

Follow
answered Jul 1, 2013 at 14:52
meiamsome meiamsome
2,896 1 1 gold badge 17 17 silver badges 19 19 bronze badges

With your solution for downloading the file, I must choose the software I want to use, it's a bit unconvenient. Is there a way to re-replace the mime as png once downloaded?

Dec 18, 2013 at 9:51

@So4ne I don't think so, it has to be an image/octet-stream to prompt the user for a download. If you get rid of that line, you'll end up with the page redirecting to the image. I would love to know if someone else knows a way to do this nicely, though.

Dec 26, 2013 at 17:59
Sep 7, 2014 at 11:44

This is great. Thanks! But what if I want to save to server and not local? Will a form file input accept the img src as something that is uploadable?

Jun 29, 2015 at 21:26

Oops. Just found the answer. Leaving the previous question in case someone else is looking as well stackoverflow.com/questions/13198131/…

Jun 29, 2015 at 21:29

function exportCanvasAsPNG(id, fileName) < var canvasElement = document.getElementById(id); var MIME_TYPE = "image/png"; var imgURL = canvasElement.toDataURL(MIME_TYPE); var dlLink = document.createElement('a'); dlLink.download = fileName; dlLink.href = imgURL; dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':'); document.body.appendChild(dlLink); dlLink.click(); document.body.removeChild(dlLink); >

Follow
answered May 22, 2015 at 9:40
david.barkhuizen david.barkhuizen
5,289 4 4 gold badges 37 37 silver badges 38 38 bronze badges
The saved file stays in .svg format. How to save it as png?
Apr 4, 2016 at 7:16

This is a nice solution except that it may not work on IE. Getting error "The data area passed to a system call is too small"

Jul 10, 2017 at 3:40
In Chrome it says "Network error", while in Firefox it works great. (On Linux)
Jan 5, 2018 at 12:55

I would use "wkhtmltopdf". It just work great. It uses webkit engine (used in Chrome, Safari, etc.), and it is very easy to use:

wkhtmltopdf stackoverflow.com/questions/923885/ this_question.pdf 

Follow
2,181 5 5 gold badges 27 27 silver badges 42 42 bronze badges
answered Feb 2, 2011 at 2:33
lepe lepe
24.8k 9 9 gold badges 101 101 silver badges 108 108 bronze badges
I'm in the wkhtmltopdf camp, too. We've been using it for archiving and its AMAZING.
Mar 30, 2012 at 15:06

How to use WKHTMLtoPDF in page that required login info ? I am using Jsreport to convert to PDF but I capture my content with HTML2Canvas ,I have issue with sending the Canvas as parameter to JSreport

Jan 2, 2017 at 0:02
@khaledDehia check: stackoverflow.com/questions/10287386/…
Jan 2, 2017 at 2:30

Here is some help if you do the download through a server (this way you can name/convert/post-process/etc your file):

-Post data using toDataURL

-Set the headers

$filename = "test.jpg"; //or png header('Content-Description: File Transfer'); if($msie = !strstr(

Capture HTML canvas as GIF/JPG/PNG/PDF?

Is it possible to capture or print what's displayed in an HTML canvas as an image or PDF? I'd like to generate an image via canvas and be able to generate a PNG from that image.

Follow 32.4k 25 25 gold badges 144 144 silver badges 173 173 bronze badges asked May 29, 2009 at 0:28 Parand Parand 104k 48 48 gold badges 152 152 silver badges 186 186 bronze badges May 23, 2016 at 16:20 Oct 8, 2016 at 22:10 Example here freakyjolly.com/… Jun 8, 2018 at 9:45 You might find canvas2image library useful for this: github.com/hongru/canvas2image Dec 29, 2018 at 1:17

If someone is looking for an answer related to React, I wrote two tutorials about it yesterday: React Component to Image and React Component to PDF.

Sep 30, 2021 at 15:35 [H1toH2] > /** * @param text * @param x * @param y * @param <"stroke"|"fill">mode * @param size, "30px" * @param font, example: "Arial" * @param color, example: "#3ae016" or "yellow" * @param alpha, 0.0 (fully transparent) to 1.0 (fully opaque) // https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors#transparency * */ AddText(text, x, y, ) < const drawFunc = (text, x, y, mode, font) => < return () => < // https://www.w3schools.com/graphics/canvas_text.asp // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillText const context = this.context const originAlpha = context.globalAlpha context.globalAlpha = alpha context.font = `$` switch (mode) < case "fill": context.fillStyle = color context.fillText(text, x, y) break case "stroke": context.strokeStyle = color context.strokeText(text, x, y) break default: throw Error(`Unknown mode:

Capture HTML canvas as GIF/JPG/PNG/PDF?

Is it possible to capture or print what's displayed in an HTML canvas as an image or PDF? I'd like to generate an image via canvas and be able to generate a PNG from that image.

Follow 32.4k 25 25 gold badges 144 144 silver badges 173 173 bronze badges asked May 29, 2009 at 0:28 Parand Parand 104k 48 48 gold badges 152 152 silver badges 186 186 bronze badges May 23, 2016 at 16:20 Oct 8, 2016 at 22:10 Example here freakyjolly.com/… Jun 8, 2018 at 9:45 You might find canvas2image library useful for this: github.com/hongru/canvas2image Dec 29, 2018 at 1:17

If someone is looking for an answer related to React, I wrote two tutorials about it yesterday: React Component to Image and React Component to PDF.

Sep 30, 2021 at 15:35 [H1toH2]

16 Answers 16

Sorted by: Reset to default

Original answer was specific to a similar question. This has been revised:

const canvas = document.getElementById('mycanvas') const img = canvas.toDataURL('image/png') 

With the value in img you can write it out as a new image like so:

document.getElementById('existing-image-id').src = img 
document.write(''); 

Follow
32.4k 25 25 gold badges 144 144 silver badges 173 173 bronze badges
answered Aug 18, 2010 at 16:37
donohoe donohoe
13.9k 4 4 gold badges 38 38 silver badges 59 59 bronze badges
one more question, how can I save the image I got in this tag to server. Any guess??
Jun 27, 2011 at 8:41

But if i use var img = canvas.toDataURL("image/jpeg"); am getting the background as complete black. How to rectify that

Dec 23, 2013 at 14:55
Oh come on. I answered this in 2009. What do you expect?
May 21, 2014 at 16:48
@donohoe actually you answered it in August 2010 🙂
May 21, 2015 at 21:59

It would use a lot less memory to do something like var img = new Image(); img.src = canvas.toDataURL(); document.body.appendChild(img); . The document.write code is making the data URL, them making a HTML string, then putting a copy of that string in the DOM, the browser then has to parse that HTML string, put another copy on the image element, then parse it again to turn the data URL into image data, then finally it can show the image. For a screen size image that's a huge amount of memory/copying/parsing. Just a suggestion

Jan 25, 2017 at 8:26

HTML5 provides Canvas.toDataURL(mimetype) which is implemented in Opera, Firefox, and Safari 4 beta. There are a number of security restrictions, however (mostly to do with drawing content from another origin onto the canvas).

So you don't need an additional library.

   

Theoretically this should create and then navigate to an image with a green square in the middle of it, but I haven't tested.

Follow
2,181 5 5 gold badges 27 27 silver badges 42 42 bronze badges
answered May 29, 2009 at 2:48
olliej olliej
35.9k 9 9 gold badges 59 59 silver badges 55 55 bronze badges
Where the image will be saved. Location in my local?
Jul 17, 2013 at 3:30

the image will be displayed as an image in your browser. You can then save it to disk or whatever. Here's a quick and dirty generic "Canvas2PNG" bookmarklet that converts the first canvas in the page to PNG and displays it in the browser in a new window: javascript:void(window.open().location = document.getElementsByTagName("canvas")[0].toDataURL("image/png"))

Apr 2, 2014 at 12:10

If the image is a few MB in size, prepare to crash your browser (I did that a while back in FireFox).

Mar 14, 2015 at 14:16
How could this be modified to render multiple images?
Oct 15, 2015 at 11:56

Data URIs have max length, so there is upper limit on the size of an image that you can put to a data url.

Jun 14, 2018 at 4:24

I thought I'd extend the scope of this question a bit, with some useful tidbits on the matter.

In order to get the canvas as an image, you should do the following:

var canvas = document.getElementById("mycanvas"); var image = canvas.toDataURL("image/png"); 

You can use this to write the image to the page:

document.write(''); 

Where "image/png" is a mime type (png is the only one that must be supported). If you would like an array of the supported types you can do something along the lines of this:

var imageMimes = ['image/png', 'image/bmp', 'image/gif', 'image/jpeg', 'image/tiff']; //Extend as necessary var acceptedMimes = new Array(); for(i = 0; i < imageMimes.length; i++) < if(canvas.toDataURL(imageMimes[i]).search(imageMimes[i])>=0) < acceptedMimes[acceptedMimes.length] = imageMimes[i]; >> 

You only need to run this once per page - it should never change through a page's lifecycle.

If you wish to make the user download the file as it is saved you can do the following:

var canvas = document.getElementById("mycanvas"); var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); //Convert image to 'octet-stream' (Just a download, really) window.location.href = image; 

If you're using that with different mime types, be sure to change both instances of image/png, but not the image/octet-stream. It is also worth mentioning that if you use any cross-domain resources in rendering your canvas, you will encounter a security error when you try to use the toDataUrl method.

Follow
answered Jul 1, 2013 at 14:52
meiamsome meiamsome
2,896 1 1 gold badge 17 17 silver badges 19 19 bronze badges

With your solution for downloading the file, I must choose the software I want to use, it's a bit unconvenient. Is there a way to re-replace the mime as png once downloaded?

Dec 18, 2013 at 9:51

@So4ne I don't think so, it has to be an image/octet-stream to prompt the user for a download. If you get rid of that line, you'll end up with the page redirecting to the image. I would love to know if someone else knows a way to do this nicely, though.

Dec 26, 2013 at 17:59
Sep 7, 2014 at 11:44

This is great. Thanks! But what if I want to save to server and not local? Will a form file input accept the img src as something that is uploadable?

Jun 29, 2015 at 21:26

Oops. Just found the answer. Leaving the previous question in case someone else is looking as well stackoverflow.com/questions/13198131/…

Jun 29, 2015 at 21:29

function exportCanvasAsPNG(id, fileName) < var canvasElement = document.getElementById(id); var MIME_TYPE = "image/png"; var imgURL = canvasElement.toDataURL(MIME_TYPE); var dlLink = document.createElement('a'); dlLink.download = fileName; dlLink.href = imgURL; dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':'); document.body.appendChild(dlLink); dlLink.click(); document.body.removeChild(dlLink); >

Follow
answered May 22, 2015 at 9:40
david.barkhuizen david.barkhuizen
5,289 4 4 gold badges 37 37 silver badges 38 38 bronze badges
The saved file stays in .svg format. How to save it as png?
Apr 4, 2016 at 7:16

This is a nice solution except that it may not work on IE. Getting error "The data area passed to a system call is too small"

Jul 10, 2017 at 3:40
In Chrome it says "Network error", while in Firefox it works great. (On Linux)
Jan 5, 2018 at 12:55

I would use "wkhtmltopdf". It just work great. It uses webkit engine (used in Chrome, Safari, etc.), and it is very easy to use:

wkhtmltopdf stackoverflow.com/questions/923885/ this_question.pdf 

Follow
2,181 5 5 gold badges 27 27 silver badges 42 42 bronze badges
answered Feb 2, 2011 at 2:33
lepe lepe
24.8k 9 9 gold badges 101 101 silver badges 108 108 bronze badges
I'm in the wkhtmltopdf camp, too. We've been using it for archiving and its AMAZING.
Mar 30, 2012 at 15:06

How to use WKHTMLtoPDF in page that required login info ? I am using Jsreport to convert to PDF but I capture my content with HTML2Canvas ,I have issue with sending the Canvas as parameter to JSreport

Jan 2, 2017 at 0:02
@khaledDehia check: stackoverflow.com/questions/10287386/…
Jan 2, 2017 at 2:30

Here is some help if you do the download through a server (this way you can name/convert/post-process/etc your file):

-Post data using toDataURL

-Set the headers

$filename = "test.jpg"; //or png header('Content-Description: File Transfer'); if($msie = !strstr(

Capture HTML canvas as GIF/JPG/PNG/PDF?

Is it possible to capture or print what's displayed in an HTML canvas as an image or PDF? I'd like to generate an image via canvas and be able to generate a PNG from that image.

Follow 32.4k 25 25 gold badges 144 144 silver badges 173 173 bronze badges asked May 29, 2009 at 0:28 Parand Parand 104k 48 48 gold badges 152 152 silver badges 186 186 bronze badges May 23, 2016 at 16:20 Oct 8, 2016 at 22:10 Example here freakyjolly.com/… Jun 8, 2018 at 9:45 You might find canvas2image library useful for this: github.com/hongru/canvas2image Dec 29, 2018 at 1:17

If someone is looking for an answer related to React, I wrote two tutorials about it yesterday: React Component to Image and React Component to PDF.

Sep 30, 2021 at 15:35 ) > context.globalAlpha = originAlpha > > this.addTextList.push(drawFunc(text, x, y, mode, font)) > /** * @description When the build is finished, you can click the filename to download the PNG or mouse enters to copy PNG to the clipboard. * */ Build(filename = "download.png") < const img = new Image() img.src = this.src img.crossOrigin = "anonymous" // Fixes: Tainted canvases may not be exported img.onload = (event) => < this.context.drawImage(event.target, 0, 0) for (const drawTextFunc of this.addTextList) < drawTextFunc() >// create a "a" node for download const a = document.createElement('a') document.querySelector('body').append(a) a.innerText = filename a.download = filename const quality = 1.0 // a.target = "_blank" a.href = this.canvas.toDataURL("image/png", quality) a.append(this.canvas) > this.canvas.onmouseenter = (event) => < // set background to white. Otherwise, background-color is black. this.context.globalCompositeOperation = "destination-over" // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation // https://www.w3schools.com/tags/canvas_globalcompositeoperation.asp this.context.fillStyle = "rgb(255,255,255)" this.context.fillRect(0, 0, this.canvas.width, this.canvas.height) this.canvas.toBlob(blob =>navigator.clipboard.write([new ClipboardItem()])) // copy to clipboard > > > class Canvas < /** * @description for do something like that: ``canvas>`` **/ constructor(w, h) < const canvas = document.createElement("canvas") document.querySelector(`body`).append(canvas) this.canvas = canvas; [this.canvas.width, this.canvas.height] = [w, h] >/** * @description If your SVG is large, you may want to know which part is what you wanted. * */ DrawGrid(step = 100) < const ctx = this.canvas.getContext('2d') const w = this.canvas.width const h = this.canvas.height // Draw the vertical line. ctx.beginPath(); for (let x = 0; x // set the color of the line ctx.strokeStyle = 'rgba(255,0,0, 0.5)' ctx.lineWidth = 1 ctx.stroke(); // Draw the horizontal line. ctx.beginPath(); for (let y = 0; y ctx.strokeStyle = 'rgba(128, 128, 128, 0.5)' ctx.lineWidth = 5 ctx.stroke() > > function ImportFontAwesome() < const range = document.createRange() const frag = range.createContextualFragment(`

if you want to run on stackoverflow and move your mouse on the picture may get error

DOMException: The Clipboard API has been blocked because of a permissions policy applied to the current document

You can copy the code on your local machine and run it again, will be fine.

SERVER["HTTP_USER_AGENT"],"MSIE")==false) header("Content-type: application/force-download");else header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename="$filename""); header("Content-Transfer-Encoding: binary"); header("Expires: 0"); header("Cache-Control: must-revalidate"); header("Pragma: public");

$data = 

Capture HTML canvas as GIF/JPG/PNG/PDF?

Is it possible to capture or print what's displayed in an HTML canvas as an image or PDF? I'd like to generate an image via canvas and be able to generate a PNG from that image.

Follow 32.4k 25 25 gold badges 144 144 silver badges 173 173 bronze badges asked May 29, 2009 at 0:28 Parand Parand 104k 48 48 gold badges 152 152 silver badges 186 186 bronze badges May 23, 2016 at 16:20 Oct 8, 2016 at 22:10 Example here freakyjolly.com/… Jun 8, 2018 at 9:45 You might find canvas2image library useful for this: github.com/hongru/canvas2image Dec 29, 2018 at 1:17

If someone is looking for an answer related to React, I wrote two tutorials about it yesterday: React Component to Image and React Component to PDF.

Sep 30, 2021 at 15:35 POST['data']; $img = imagecreatefromstring(base64_decode(substr($data,strpos($data,',')+1)));
$width = imagesx($img); $height = imagesy($img); $output = imagecreatetruecolor($width, $height); $white = imagecolorallocate($output, 255, 255, 255); imagefilledrectangle($output, 0, 0, $width, $height, $white); imagecopy($output, $img, 0, 0, 0, 0, $width, $height); imagejpeg($output); exit(); 
imagesavealpha($img, true); imagepng($img); die($img); 

Follow
1 1 1 silver badge
answered Jul 22, 2013 at 17:33
user669677 user669677

This is the other way, without strings although I don't really know if it's faster or not. Instead of toDataURL (as all questions here propose). In my case want to prevent dataUrl/base64 since I need a Array buffer or view. So the other method in HTMLCanvasElement is toBlob . (TypeScript function):

 export function canvasToArrayBuffer(canvas: HTMLCanvasElement, mime: string): Promise  < return new Promise((resolve, reject) =>canvas.toBlob(async (d) => < if (d) < const r = new FileReader(); r.addEventListener('loadend', e => < const ab = r.result; if (ab) < resolve(ab as ArrayBuffer); >else < reject(new Error('Expected FileReader result')); >>); r.addEventListener('error', e => < reject(e) >); r.readAsArrayBuffer(d); > else < reject(new Error('Expected toBlob() to be defined')); >>, mime)); > 

Another advantage of blobs is you can create ObjectUrls to represent data as files, similar to HTMLInputFile's 'files' member. More info:

Follow
18k 6 6 gold badges 54 54 silver badges 81 81 bronze badges
answered Sep 23, 2019 at 6:38
cancerbero cancerbero
6,819 1 1 gold badge 32 32 silver badges 24 24 bronze badges
This answer must be marked as the correct one and need to be upvoted. Thanks!
Aug 11, 2020 at 22:23

Another interesting solution is PhantomJS. It's a headless WebKit scriptable with JavaScript or CoffeeScript.

One of the use case is screen capture : you can programmatically capture web contents, including SVG and Canvas and/or Create web site screenshots with thumbnail preview.

The best entry point is the screen capture wiki page.

Here is a good example for polar clock (from RaphaelJS):

>phantomjs rasterize.js http://raphaeljs.com/polar-clock.html clock.png 

Do you want to render a page to a PDF ?

> phantomjs rasterize.js 'http://en.wikipedia.org/w/index.php?title=Jakarta&printable=yes' jakarta.pdf 

Follow
answered May 21, 2013 at 11:28
Cybermaxs Cybermaxs
24.4k 8 8 gold badges 83 83 silver badges 112 112 bronze badges

+1: PhantomJS is simple, well documented and well thought-out system, perfect for this job. It allows much more than just grabbing a canvas too - for instance, you can modify the page or part of it (through JS) before grabbing so make it look just the way you want it. Perfect!

Sep 18, 2013 at 6:57
PhantomJs is now obsolete
May 21, 2018 at 6:46

PhantomJS is not "obsolete" - it is unmaintained. It still supports most ES6 stuff, and is still the only modern/decent headless browser that works on x86 and does not need compiling. Therefore it still the only [proper] headless browser that works on various embedded or lightweight distros/systems.

Aug 5, 2020 at 10:31

If you are using jQuery, which quite a lot of people do, then you would implement the accepted answer like so:

var canvas = $("#mycanvas")[0]; var img = canvas.toDataURL("image/png"); $("#elememt-to-write-to").html(''); 

Follow
2,181 5 5 gold badges 27 27 silver badges 42 42 bronze badges
answered Sep 7, 2013 at 11:01
Pattle Pattle
5,983 8 8 gold badges 33 33 silver badges 57 57 bronze badges
Do note that the only usage of jQuery here is the selection of the canvas. .toDataURL is native JS.
Jul 9, 2014 at 0:32
I have save issue some one can help me see this link :stackoverflow.com/questions/25131763/…
Aug 11, 2014 at 16:22

Pure (100%) jQuery solution is the following: $('').attr('src',$('#mycanvas')[0].toDataURL('image/png')).appendTo($('#element-to-write-to').empty()); Exactly one line.

Mar 21, 2015 at 5:57

The key point is

And I want to provide an example for someone like me who wants to save SVG to PNG(also can add some text if you wish), which may be from an Online source or font-awesome icon, etc.

[/H1toH2]

Paint your own photo with a paint by numbers custom kit

Daily Dose of Challenge: Inspire Yourself

Before we give you a handful of ideas on easy things to paint on a canvas, let’s go through a little bit of an ice breaker that will help in giving you plenty of inspiration as well as restore your creative juices.

Many artists reveal that whenever they run out of ideas to paint, they often go outside and bring a piece of paper (or a small artist’s notebook) and a pen with them wherever they go. Some artists sketch while they commute in public transportation, looking at their windows or the people around them. Some go to the park and sketch whatever’s in front of them while some take on a trip to a place where they can reconnect with nature, bringing their easel, canvas, and other art supplies along with them.

So here’s the challenge for you: try doing the same thing. Bring a piece or two of paper, a small notebook that will be better, and sketch outside. The sketch doesn’t have to be perfect, it only teaches you to be inspired so that when you go back inside your room or studio again, at least you have a preliminary sketch or blueprint on what to paint.

You’re not only improving your creativity while getting inspired because by doing this, but you’re also improving a skill necessary for artists which is sketching.

A photo of a man writing on a paper

What are Some Easy Things to Paint on a Canvas?

1. Still life of fruits:

Sill life is one of the most common and important principal genres of the Western art world. Commonly, still, lives are paintings of inanimate objects such as fruits, wine, bottles, baskets of flowers, and many more. Many people think that painting these is hard, however, with the right practice and objects in front of you, all will be well. The key to a great still-life painting is to have the actual objects in front of you while painting. That way, it can serve as a model and you could really study the lighting, values, hues, etc. of your background.

An art picture still life painting of fruits and glass bottles

Paint your own photo with a paint by numbers custom kit



2. Dream catcher:

In Native American culture, these are hung near the window or bedpost as a form of protection from bad dreams and to help you welcome good ones instead. Dream catchers are a pretty good display somewhere in your room but have you tried painting one? Surely, by painting one, your room will look like a bohemian wonderland, perfect as a room decoration.

An illustration painting of brown haired woman in a blue dress


3. Ocean waves:

Serene. Calm. Quiet. That’s how most of us describe how the ocean feels. If you wanna take yourself on a trip to the ocean when you have no time, try to reminisce about your favorite moments with the ocean and paint the waves that you’ve seen. It doesn’t have to be an accurate depiction, it can even be abstract if you prefer. Thus, working with ocean waves couldn’t be any simpler because you only have to work with a few colors. Also, it’s a great way to practice your brushwork and blending skills too, which is truly one of the easy things to paint on a canvas for beginners.

A blue colored abstract painting

Paint your own photo with a paint by numbers custom kit

4. Galaxy-inspired Paint Pouring:

Who doesn’t love acrylic paint pouring? It’s a great, easy, and fun way to make your room extra sophisticated. The simplicity of the painting process with the unpredictability of the painting’s final outcome is one of the things that make this art interesting. Not to mention the thousands of color combinations that you can create, as well as the different styles that you can employ with this technique. One of the most popular color combinations for this technique is galaxy-inspired colors, which are often violet, black, white, blue, and yellow.

Don’t forget to put gold flakes once the painting is thoroughly dried so that it would look sparkly like the galaxy!

An orange multi colored abstract painting

5. Field of flowers:

Let your personality and artistic capabilities bloom by painting your favorite flowers in different shapes, colors, and sizes. Florals have been a common yet very interesting subject for painting– it never ceases to amaze people because of the simplicity and elegance that it brings to a wall. Thus, you can employ different techniques while painting this subject to add depth and texture, such as painting it impasto style or with palette knives.

A photo of a rose flowers painter paint

Paint your own photo with a paint by numbers custom kit

Give Yourself (or Your Loved Ones) the Gift of Painting

The list of easy things to paint on the canvas above will surely help you improve your painting skills while contributing an additional aesthetic to your wall once you’re ready to display your finished painting.

If you want to improve your artistic skills even further, you can use paint by numbers kits. Apart from the multitude of design selections to choose from, it also gives you the freedom to choose your own photo that will be turned into a customized canvas that you can paint and enjoy. These kits will help you learn the basic foundation of painting such as color theory, blending, brushwork, and the “number technique” where you assign particular colors to a specific number on the canvas to help you easily remember your hues.

To know more about paint by numbers kits, click here.

Colin Wynn
the authorColin Wynn

Leave a Reply