html canvas导出png,如何使用(仅)Javascript将HTML Canvas保存为命名.PNG

尝试这样的事情:

function downloadCanvas(link, canvasId, filename) {

link.href = document.getElementById(canvasId).toDataURL();

link.download = filename;

}

document.getElementById('download').addEventListener('click', function() {

downloadCanvas(this, 'canvas', 'test.png');

}, false);

这是一个工作版本

/**

* Ken Fyrstenberg Nilsen

* Abidas Software

*/

var canvas = document.getElementById('canvas'),

ctx = canvas.getContext('2d');

/**

* Demonstrates how to download a canvas an image with a single

* direct click on a link.

*/

function doCanvas() {

/* draw something */

ctx.fillStyle = '#f90';

ctx.fillRect(0, 0, canvas.width, canvas.height);

ctx.fillStyle = '#fff';

ctx.font = '40px sans-serif';

ctx.fillText('Code Project', 10, canvas.height / 2 - 15);

ctx.font = '16px sans-serif';

ctx.fillText('Click link below to save this as image', 15, canvas.height / 2 + 35);

}

/**

* This is the function that will take care of image extracting and

* setting proper filename for the download.

* IMPORTANT: Call it from within a onclick event.

*/

function downloadCanvas(link, canvasId, filename) {

link.href = document.getElementById(canvasId).toDataURL();

link.download = filename;

}

/**

* The event handler for the link's onclick event. We give THIS as a

* parameter (=the link element), ID of the canvas and a filename.

*/

document.getElementById('download').addEventListener('click', function() {

downloadCanvas(this, 'canvas', 'test.png');

}, false);

/**

* Draw something to canvas

*/

doCanvas();

body {

background-color:#555557;

padding:0;

margin:0;

overflow:hidden;

font-family:sans-serif;

-webkit-user-select: none;

-khtml-user-select: none;

-moz-user-select: none;

-ms-user-select: none;

user-select: none;

}

canvas {

border:1px solid #000;

display: block;

}

#download {

float:left;

cursor:pointer;

color:#ccc;

padding:3px;

}

#download:hover {

color:#fff;

}

Sorry, no canvas available

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值