如何在windows 8 metro应用程序中将html5画布保存为图像文件?

isa*_*isa 1 javascript canvas microsoft-metro windows-8

var myImage = canvas.toDataURL("image/png");
Run Code Online (Sandbox Code Playgroud)

我认为myImage现在以png格式编码的图像字节如何保存myImage为文件(在图像文件夹中)?

Dom*_*ton 6

而不是使用.toDataUrl,你需要使用.msToBlob:

var blob = canvas.msToBlob();
Run Code Online (Sandbox Code Playgroud)

然后,您需要将其写入磁盘:

var output;
var input;
var outputStream;

Windows.Storage.ApplicationData.current.localFolder.createFileAsync("yourFile", 
          Windows.Storage.CreationCollisionOption.replaceExisting).
    then(function(file) {
        return file.openAsync(Windows.Storage.FileAccessMode.readWrite);
    }).then(function(stream) {
        outputStream = stream;
        output = stream.getOutputStreamAt(0);
        input = blob.msDetachStream();
        return Windows.Storage.Streams.RandomAccessStream.copyAsync(input, output);
    }).then(function() {
        return output.flushAsync();
    }).done(function() {
        input.close();
        output.close();
        outputStream.close();
    });
Run Code Online (Sandbox Code Playgroud)

在应用程序应用程序数据文件夹中,您现在可以将映像写入磁盘.

如果你想把它放在其他地方 - 比如我的照片等 - 那么你只需要使用其他存储文件夹.请在此处查看示例.请注意,要访问图片库,您需要将该功能添加到清单(只是VS中package.appxmanifest编辑器中的复选框)

还有许多其他成像选项可用于更复杂的输出文件操作.有关代码,请参阅成像示例.