我已经为单个div尝试了html2canvas,它运行正常。现在我在页面上有2个图表,所以我想在单独的画布中捕获两个div并将其作为图像传递。我试过跟随,但它总是设置为undefined。我不知道是什么问题。当我在firebug中进入调试模式时,我发现它首先没有进入html2canvas,它进入ajax并执行ajax之后进入html2canvas。
$("#getPdf").click(function () {
var imageChart1, imageChart2;
html2canvas($('#loadchart1'), {
onrendered: function (canvas1) {
imageChart1 = canvas1.toDataURL("image/png");
alert(imageChart1);
imageChart1 = imageChart1.replace('data:image/png;base64,', '');
}
});
html2canvas($('#loadchart2'), {
onrendered: function (canvas2) {
imageChart2 = canvas2.toDataURL("image/png");
imageChart2 = imageChart2.replace('data:image/png;base64,', '');
}
});
if (imageChart1 != undefined && imageChart2 != undefined) {
$.ajax({
type: 'POST',
url: "/ChartReport/UploadImage",
data: ' { "image1" : "' + imageChart1 + '","image2":"' + imageChart2 + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image saved successfully !');
}
});
}
});
编辑异步后:
$("#getPdf").click(function () {
var count = 0;
var imageArray = new Array("#loadchart1", "#loadchart2");
async.parallel([
function (callback) {
for (var i = 0; i < imageArray.length; i = i + 1) {
html2canvas($(imageArray[i]), {
onrendered: function (canvas) {
var imageChart1 = canvas.toDataURL("image/png").replace(' :image/png;base64,', '');
$.ajax({
type: 'POST',
url: "/ChartReport/UploadImage",
data: ' { "image1" : "' + imageChart1 + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
count = count + 1;
}
});
}
});
}
callback();
},
function (callback) {
if (count != 0) {
$.ajax({
type: 'POST',
url: "/ChartReport/makePDF",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image saved successfully !');
}
});
}
callback();
} ],
function (err, results) {
alert(results[0]);
});
});
注意:div loadchart1在局部视图中,它在document.ready()
上加载答案 0 :(得分:1)
好的,我不知道html2canvas库,但是看起来出了什么问题是你在代码中混淆了流程。您在html2canvas函数的回调中分配给imageChartN
,因此在分配变量之前已到达if
。您应该查看的内容是async.js
并使用async.parallel
功能。