项目结构:
源码:
DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>将图片保存到本地title>
head>
<body>
<canvas id="canvas">canvas>
<br />
<input type="button" id="button-save-as" value="Save as..." />
<script type="text/javascript">
window.onload = function(event) {
main();
}
function main() {
const canvas = document.querySelector("#canvas");
const canvasContext = canvas.getContext("2d");
{
// 先在 canvas 上面画一张图片
const image = new Image();
image.onload = (event) => {
// console.log(event);
canvas.width = image.width;
canvas.height = image.height;
canvasContext.drawImage(image, 0, 0);
}
image.src = "img/transformers.jpg";
}
{
const buttonSaveAs = document.getElementById('button-save-as');
buttonSaveAs.onclick = (event) => {
canvas.toBlob(function (blob) {
// https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob
const objectURL = URL.createObjectURL(new Blob([ blob ], { type: "image/png" }));
const anchor = document.createElement('a');
anchor.href = objectURL;
anchor.download = "Filename.png";
anchor.click();
URL.revokeObjectURL(objectURL);
}, "image/png", 1);
};
}
}
script>
body>
html>