加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

如何使用(仅)Javascript将HTML Canvas保存为命名.PNG

发布时间:2020-12-14 22:39:16 所属栏目:资源 来源:网络整理
导读:我正在使用Html Canvas和JavaScript编写图像编辑器(只是为了更多地了解这两种语言). 我一直在搜索,但我发现的问题都没有奏效. 这就是我现在所拥有的: PicName是该人可以输入文件名的字段.正如您所看到的(如果您尝试一下)我已经让PicName选择器工作了.所以现

我正在使用Html Canvas和JavaScript编写图像编辑器(只是为了更多地了解这两种语言).
我一直在搜索,但我发现的问题都没有奏效.
这就是我现在所拥有的:

 

PicName是该人可以输入文件名的字段.正如您所看到的(如果您尝试一下)我已经让PicName选择器工作了.所以现在我只需要保存带有名称的文件.

最佳答案
尝试这样的事情:

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,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,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',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;
	}

	

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读