这个其实是在做上一篇需求的时候先做出来的,但是由于某些原因不符合需求,所以这个就当做练习弄出来了。
demo效果图如下:
注意点跟上一篇[http://www.jianshu.com/p/651c786dd81f]是一样的,这里不做介绍。
直接上代码:
html:
<textarea id="editor_id" name="content" style="width:700px;height:300px;" placeholder="请输入内容"></textarea>
<button onclick="save()">将富文本编辑器里的内容提取到页面指定的容器中</button>
<button onclick="btnSave()">转成图片</button>
<div id="image" style="display: none;"></div>
<div style="width:600px;height: 200px;border:1px solid #000;margin-top:10px;padding:5px;">
<div id="showContent" style="width:100%;height:100%"></div>
</div>
script:
<script src="../js/jquery.min.js"></script>
<script src="kindeditor.js"></script>
<script src="lang/zh_CN.js"></script>
<script src="../js/jsPdf.debug.js"></script>
<script src="../js/html2canvas.js"></script>
<script src="../js/canvas2image.js"></script>
<script src="../js/base64.js"></script>
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"]');
// 同步数据后可以直接取得textarea的value
editor.sync();
function save() {
var html = editor.html();
var showContent = document.getElementById('showContent');
showContent.innerHTML = html;
}
function btnSave() {
/*生成canvas图形*/
// 获取内容id
var content = document.getElementById("showContent");
// 进行canvas生成
html2canvas(content, {
onrendered: function (canvas) {
timestamp = Date.parse(new Date());
thecanvas = "thecanvas" + timestamp
//添加属性
canvas.setAttribute('id', thecanvas);
//读取属性值
// var value= canvas.getAttribute('id');
//将生成的canvas放入指定的div中
document.getElementById('image').appendChild(canvas);
}
});
//下载
Download(thecanvas);
}
function Download(thecanvas) {
var oCanvas = document.getElementById(thecanvas);
/*自动保存为png*/
// 获取图片资源
var img_data1 = Canvas2Image.saveAsPNG(oCanvas, true).getAttribute('src');
// saveFile(img_data1);
// 保存文件函数
var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
save_link.href = img_data1;
save_link.download = thecanvas;
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
save_link.dispatchEvent(event);
/*下面的为原生的保存,不带格式名*/
// 这将会提示用户保存PNG图片
// Canvas2Image.saveAsPNG(oCanvas);
}