Comments: The main idea of saving the HTML5 Canvas content as an image is to use Canvas's own API-toDataURL (). The specific implementation is as follows. If you are interested, refer to the following, I hope to help you with the main idea is to use Canvas's own API-toDataURL () for implementation.
The HTML + JavaScript code is simple.
The Code is as follows:
<Html>
<Meta http-equiv = "X-UA-Compatible" content = "chrome = 1">
<Head>
<Script>
Window. onload = function (){
Draw ();
Var saveButton = document. getElementById ("saveImageBtn ");
BindButtonEvent (saveButton, "click", saveImageInfo );
Var dlButton = document. getElementById ("downloadImageBtn ");
BindButtonEvent (dlButton, "click", saveAsLocalImage );
};
Function draw (){
Var canvas = document. getElementById ("thecanvas ");
Var ctx = canvas. getContext ("2d ");
Ctx. fillStyle = "rgba (125, 46,138, 0.5 )";
Ctx. fillRect (100,100 );
Ctx. fillStyle = "rgba (0,146, 38, 0.5 )";
Ctx. fillRect (58, 74,125,100 );
Ctx. fillStyle = "rgba (0, 0, 0, 1)"; // black color
Ctx. fillText ("Gloomyfish-Demo", 50, 50 );
}
Function bindButtonEvent (element, type, handler)
{
If (element. addEventListener ){
Element. addEventListener (type, handler, false );
} Else {
Element. attachEvent ('on' + type, handler );
}
}
Function saveImageInfo ()
{
Var mycanvas = document. getElementById ("thecanvas ");
Var image = mycanvas. toDataURL ("image/png ");
Var w = window. open ('about: blank ', 'image from canvas ');
Using Doc ument. write (" ");
}
Function saveAsLocalImage (){
Var myCanvas = document. getElementById ("thecanvas ");
// Here is the most important part because if you dont replace you will get a DOM 18 exception.
// Var image = myCanvas. toDataURL ("image/png"). replace ("image/png", "image/octet-stream; Content-Disposition: attachment?filename=foobar.png ");
Var image = myCanvas. toDataURL ("image/png"). replace ("image/png", "image/octet-stream ");
Window. location. href = image; // it will save locally
}
</Script>
</Head>
<Body bgcolor = "# E6E6FA">
<Div>
<Canvas width = 200 height = 200 id = "thecanvas"> </canvas>
<Button id = "saveImageBtn"> Save Image </button>
<Button id = "downloadImageBtn"> Download Image </button>
</Div>
</Body>
</Html>
The running effect is as follows::