生成div的图像并另存为 [英] Generate an image of a div and Save as
问题描述
我想创建一个输入按钮保存图像":
I'd like to create an input button "Save image" that :
- 拍摄div的屏幕截图
- 要求在用户计算机上另存为"
我已经找到了如何使用html2canvas创建潜水屏幕并在新标签页中打开它的方法,该方法非常完美:
I've found how to create a screen of a dive using html2canvas and to open it in a new tab, it works perfectly :
function printDiv2(div)
{
html2canvas((div), {
onrendered: function(canvas) {
var img = canvas.toDataURL();
window.open(img);
}
});
}
但是对于您来说,另存为一部分是困难的一部分...我发现了有趣的主题,因为我是JS(和对象)编码的新手,所以我有点困惑...我想我必须使用FileSaver.js并创建一个新的Blob http://eligrey.com/blog/post/saving-generation-files -on-the-client-side/
But for thee Save as part, is a kind of the tough part... I've found interesting topics, as I'm new in JS (and object) coding, I'm a little bit confused... I think I'll have to use the FileSaver.js and to create a new blob http://eligrey.com/blog/post/saving-generated-files-on-the-client-side/
但是我不知道如何在html2canvas中实现saveAs,如何正确投射新的Blob ...
But I don't get how to implement the saveAs in my html2canvas, how to cast properly a new blob...
function printDiv2(div)
{
html2canvas((div), {
onrendered: function(canvas) {
var img = canvas.toDataURL();
window.open(img);
var blob = new Blob(img, {type: "image/jpeg"});
var filesaver = saveAs(blob, "my image.png");
}
});
}
我还尝试通过提取base64生成的URL来对此进行处理,但是对于我来说,要理解一切都太复杂了: > http://bl.ocks.org/nolanlawson/0eac306e4dac2114c752
Also I tried to do something with this, by extracting the base64 generated URL, but it's too complicated for me to understand everyting : http://bl.ocks.org/nolanlawson/0eac306e4dac2114c752
但是有人给我一些提示,请帮我吗?
But someone give me a few tips and help me please ?
推荐答案
如果可以帮助您,以下是最终代码:
Here is the final code, if it can helps you :
function PrintDiv(div)
{
html2canvas((div), {
onrendered: function(canvas) {
var myImage = canvas.toDataURL();
downloadURI(myImage, "MaSimulation.png");
}
});
}
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
//after creating link you should delete dynamic link
//clearDynamicLink(link);
}
这篇关于生成div的图像并另存为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!