我知道您不应该在Javascript中进行屏蔽,而且我从来没有摆脱过不必要的重构。但是我遇到了一些我不知道如何处理回调的东西。我正在尝试将Downloadify与html2canvas一起使用(这仅适用于IE,无法在IE中下载数据URI)。您必须指定一个数据函数,以便Flash对象知道要下载的内容。不幸的是,html2canvas是异步的。我需要能够等到onrendered事件填满后才能获取数据URI。

$('#snapshot').downloadify({
        filename: function(){
            return 'timeline.png';
        },
        data: function(){
            var d = null;
            html2canvas($('#timeline'),{
                onrendered:function(canvas){
                    d = canvas.toDataURL();
                }
            });

            //need to be able to block until d isn't null

            return d;
        },
        swf: '../static/bin/downloadify.swf',
        downloadImage: '../static/img/camera_icon_32.png?rev=1',
        width: 32,
        height: 32,
        transparent: true,
        append: false
});

我乐于接受其他方法的建议,但我遇到了麻烦。

编辑-一些评论似乎似乎需要有关Downloadify的更多信息(https://github.com/dcneiner/Downloadify)。 Downloadify是一个Flash对象,可用于触发浏览器的“另存为”窗口。 downloadify()函数只是简单地将Flash对象初始化并将<object/>标签粘贴在元素中。由于它是Flash对象,因此您不能在不引起安全违规的情况下触发Javascript事件。

我仅将其用于IE,以下载Canvas元素的图像。在所有其他浏览器中,我只能使用数据URI,但是IE是一朵特殊的花。

最佳答案

对于一整夜试图让HTML5功能在IE9上运行的可怜人,这就是我最终使用的方法。我可以使用它,因为我们不太担心IE用户获得的用户友好程度较低,这是一个内部应用程序。但是,YMMV。

基本上,当返回字符串为空时,Downloadify将不执行任何操作。因此,由于html2canvas呈现的异步特性,用户第一次单击时不会发生任何事情。第二次(假设渲染已完成,如果没有渲染,直到渲染完成,否则将继续发生),该值不为空,并且保存继续。我使用onCancel和onCoplete回调再次清空该值,以确保用户下次尝试保存图像时,图像不会太陈旧。

这不能说明用户在两次单击之间以某种方式更改DOM的情况,但是我不知道该怎么办。我对此并不感到骄傲,但是IE就是它的本质。它可以正常工作,现在就足够了。

    var renderedPng = '';
    var rendering = false;

    $('#snapshot').downloadify({
        filename: function(){
            return 'timeline.png';
        },
        data: function(){
            if(!rendering && renderedPng == ''){
                rendering = true;
                html2canvas($('#timeline'),{
                    onrendered:function(canvas){
                        renderedPng = canvas.toDataURL().replace('data:image/png;base64,','');
                        rendering = false;
                    }
                });
            }
            return renderedPng;
        },
        onComplete:function(){
            renderedPng = '';
        },
        onCancel: function(){
            renderedPng = '';
        },
        dataType: 'base64',
        swf: '../static/bin/downloadify.swf',
        downloadImage: '../static/img/camera_icon_32.png?rev=1',
        width: 32,
        height: 32,
        transparent: true,
        append: false
    });

08-18 05:22
查看更多