将 canvas 作为图片下载
思路是将 canvas 转化为 base64 链接,通过模仿 a 标签的 download 属性进行下载
// https://stackoverflow.com/questions/18480474/how-to-save-an-image-from-canvas
function download(canvas, filename) {var lnk = document.createElement('a'), e
lnk.download = filename
lnk.href = canvas.toDataURL('image/png;base64')
if(document.createEvent) {e = document.createEvent('MouseEvents')
e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
lnk.dispatchEvent(e)
} else if(lnk.fireEvent) {lnk.fireEvent('onclick')
}
}
放一个 html 的 Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Download Cavans</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,body{
height: 100%;
width: 100%;
}
.wrapper{
width: 100%;
height: 100%;
padding: 100px;
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
}
.button{
width: 100px;
height: 40px;
display: flex;
justify-content: center;
align-items: center;
border: 1px solid #ddd;
box-shadow: 2px 2px 14px #333;
cursor: pointer;
user-select: none;
transition: all .3s;
}
.button:hover{transform: skew(-15deg);
}
</style>
</head>
<body>
<div class="wrapper">
<div class="button">Download</div>
</div>
<script>
var wrapper = document.querySelector('.wrapper')
var canvas = document.createElement('canvas')
canvas.width = 500
canvas.height = 500
var ctx = canvas.getContext('2d')
ctx.fillStyle = 'rgba(0, 0, 225, .6)'
ctx.fillRect(0, 0, 500, 500)
ctx.fillStyle = 'rgba(225, 0, 0, .6)'
ctx.font = '600 40px Arial'
ctx.fillText('Canvas', 100, 100)
wrapper.appendChild(canvas)
function download(canvas, filename) {var lnk = document.createElement('a'), e
lnk.download = filename
lnk.href = canvas.toDataURL('image/png;base64')
if(document.createEvent) {e = document.createEvent('MouseEvents')
e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
lnk.dispatchEvent(e)
} else if(lnk.fireEvent) {lnk.fireEvent('onclick')
}
}
document.querySelector('.button').onclick = () => {download(canvas, 'image.png')
}
</script>
</body>
</html>