html页面一个canvas画布:
<canvas id="canvas"></canvas> <button class="button-balanced" id="save">save</button> <br /> <a href="" download="canvas_love.png" id="save_href"> <img src="" id="save_img"/> </a>
对应的js代码实现:
var c=document.getElementById("canvas"); function drawLove(canvas){ let ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.fillStyle="#E992B9"; ctx.moveTo(75,40); ctx.bezierCurveTo(75,37,70,25,50,25); ctx.bezierCurveTo(20,25,20,62.5,20,62.5); ctx.bezierCurveTo(20,80,40,102,75,120); ctx.bezierCurveTo(110,102,130,80,130,62.5); ctx.bezierCurveTo(130,62.5,130,25,100,25); ctx.bezierCurveTo(85,25,75,37,75,40); ctx.fill(); } drawLove(c); var butSave = document.getElementById("save"); butSave.onclick=function(){ var svaeHref = document.getElementById("save_href"); /* * 传入对应想要保存的图片格式的mime类型 * 常见:image/png,image/gif,image/jpg,image/jpeg */ var img = document.getElementById("save_img"); var tempSrc = canvas.toDataURL("image/png"); svaeHref.href=tempSrc; img.src=tempSrc; };
点击save按钮后,显示图片,点击图片即可弹出下载对话框。
效果如下:
以上就是canvas转存为图片实例教程的详细内容,更多请关注二当家的素材网其它相关文章!
友情提示:垃圾评论一律封号 加我微信:826096331拉你进VIP群学习群