我在按钮单击事件上使用html2canvas创建图像。但是我必须单击两次按钮才能将图像下载到我的系统。我可以在第一次点击时执行此操作吗?我是javascript / jquery的新手,因此非常感谢所有指针。
<script>
$("#btn").on('click', function () {
html2canvas($("#maintag"), {
onrendered: function (canvas) {
var myCanvas = canvas;
var initImage = myCanvas.toDataURL("image/png");
var dnldImage = initImage.replace(/^data:image\/[^;]/, 'data:application/octet-stream');
$("#btn").attr("download", "test.png").attr("href", dnldImage);
}
});
});
</script>
答案 0 :(得分:2)
您可以模拟在代码内部单击第二个按钮:
<script>
$("#btn").on('click', function () {
html2canvas($("#maintag"), {
onrendered: function (canvas) {
var myCanvas = canvas;
var initImage = myCanvas.toDataURL("image/png");
var dnldImage = initImage.replace(/^data:image\/[^;]/, 'data:application/octet-stream');
$("#btn").attr("download", "test.png").attr("href", dnldImage);
$("#btn").click();
}
});
});
答案 1 :(得分:1)
您可以在页面加载时触发它。将此触发器添加到事件结束:
month-year name a b c
2018-01 X 3 3.5 0.71
Y 5 5 1.41
2018-02 X 19 4.5 0.96
Y 29 9.5 3.86
}).click(); // .trigger('click');
答案 2 :(得分:0)
<script type="text/javascript">
$("#btn").on('click', function () {
html2canvas($("#maintag"), {
onrendered: downloadCanvas
});
});
function downloadCanvas(canvas) {
var link = document.createElement('a');
link.setAttribute('download', 'test.png');
link.setAttribute('href', canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"));
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
</script>