html2canvas 将图片转为png,将html保存为png图片(html2canvas.js,canvas2image.js)

本文介绍如何利用html2canvas和canvas2image.js将富文本编辑器的内容保存为HTML页面,并进一步转化为PNG图片。由于html2canvas的限制,不支持跨域图片、iframe、Flash和部分浏览器,但可以实现表格等内容的转换。文中提供了从KindEditor获取内容、设置HTML、转换图片的完整代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本来需求是直接通过获取富文本编辑器里的内容,保存为图片的,但是因为自己技术水的问题吧,只能折中,将富文本编辑器里的内容保存到html页面,再将指定的区域内容保存为图片。因为本人的需求仅仅是对表格及其内容进行转换操作,没有涉及太多东西。

demo效果图如下:

651c786dd81f

image.png

1.富文本编辑器用的是KindEditor(http://kindeditor.net/doc.php),按照官网步骤将富文本显示出来,这里不做介绍。

2.使用的到的插件有html2canvas.js,canvas2image.js,base64.js,可以自己到github去下载。

3.说明

html2canvas,目前该插件还在开发中,暂不支持带有图片的div转换。图片会被忽略

对一些的默认样式的支持可能不那么尽如人意,建议自己定义样式,

不支持iframe

不支持跨域图片

不能在浏览器插件中使用

部分浏览器上不支持SVG图片

不支持Flash

不支持古代浏览器和IE,如果你想确认是否支持某个浏览器,可以用它访问 http://deerface.sinaapp.com/ 试试

整个案例具体代码如下:

html:

将富文本编辑器里的内容提取到页面指定的容器中

将容器中的内容转成图片

图片显示:

script:

//富文本编辑器设置(具体参考# [编辑器初始化参数](http://kindeditor.net/docs/option.html#id60)

)

KindEditor.ready(function (K) {

window.editor = K.create('#editor_id', {

//配置编辑器的工具栏

items: [

'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',

'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',

'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',

'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',

'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',

'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',

'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',

'anchor', 'link', 'unlink', '|', 'about'

]

});

});

var editor = K.create('textarea[name="content"]', options);

// 同步数据后可以直接取得textarea的value

editor.sync();

//将富文本编辑器里的内容提取到页面指定的容器中

function save() {

var html = editor.html();

var showContent = document.getElementById('showContent');

showContent.innerHTML = html;

}

//设置一个变量保证生成图片ID的唯一

var timestamp;

//保存生成图片的ID值

var valueId = $('input').val();

//将容器中的内容转成图片

function example1() {

//将富文本编辑器里的内容提取到页面指定的容器中

var html = editor.html();

$('#showContent').html(html);

//获取当前时间戳作为图片ID的唯一值

timestamp = Date.parse(new Date());

//启用此条则只截取指定区域的图

html2canvas($('#showContent'), {

allowTaint: true,

taintTest: false,

onrendered: function (canvas) {

var PicId = "picId" + timestamp;

//保证只有一张图片生成

if(valueId){

$('img').remove();

valueId = PicId;

}else{

valueId = PicId;

}

//生成base64图片数据

var dataUrl = canvas.toDataURL();

var newImg = document.createElement("img");

newImg.src = dataUrl;

newImg.id = valueId;

//添加生成的图片

document.body.append(newImg);

}

});

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值