canvas.toDataURL(“ image / png”)-如何工作以及如何对其进行优化 [英] canvas.toDataURL("image/png") - how does it work and how to optimize it

查看:424
本文介绍了canvas.toDataURL(“ image / png”)-如何工作以及如何对其进行优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人知道

canvas.toDataURL("image/png"); 

有效吗?我想更好地理解,因为有时它似乎确实使我的计算机运行缓慢。
有没有一种方法可以在优化之前或之后优化base64图像以获得更好的性能?

works? I want to understand better because at times it seems to really slow my computer down. Is there a way to optimize the base64 image before during or after to get better performance ?

function base64(url) {
    var dataURL;
    var img = new Image(),
        canvas = document.createElement("canvas"),
        ctx = canvas.getContext("2d"),
        src = url; 
    img.crossOrigin = "Anonymous";
    img.onload = function () {
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        var dataURL = canvas.toDataURL('image/png');
        preload(dataURL);
        canvas = null;
    };
    img.src = url;
}

基本上这是我的功能,但我想看看是否有办法使此过程的执行效果更好,或者是否可以替代canvas.toDataURL('image / png');

Basically this is my function but I wanted to see if there was a way to make this process perform better or if there was an alternative to canvas.toDataURL('image/png');

谢谢

推荐答案

toDataURL()在(同步)调用时执行以下操作:

toDataURL() does the following when called (synchronously):


  • 根据请求或支持的文件类型创建文件头(默认为PNG)

  • 根据文件格式压缩位图数据

  • 将生成的二进制文件编码为Base-64字符串

  • 添加data-uri标头并返回结果

  • Creates a file header based on the file type requested or supported (defaults to PNG)
  • Compresses the bitmap data based on file format
  • Encodes the resulting binary file to Base-64 string
  • Prepends the data-uri header and returns the result

将data-uri设置为源时(异步):

When setting a data-uri as source (asynchronously):


  • 已验证字符串

  • Base-64部分已分离并解码为二进制格式

  • 已验证二进制文件,然后对其进行了解析和未压缩

  • 结果位图设置为Image元素和适当的回调

  • String is verified
  • Base-64 part is separated and decoded to binary format
  • Binary file verified then parsed and uncompressed
  • Resulting bitmap set to Image element and proper callbacks invoked

这些步骤非常耗时,由于它们是内部的,因此我们无法出于任何原因使用它们。由于已经对其进行了很好的优化,因为可以在上下文中使用它们,因此我们几乎无法对其进行优化。

These are time-consuming steps and as they are internal we cannot tap into them for any reason. As they are pretty optimized as they are given the context they work in there is little we can do to optimize them.

您可以使用JPEG与PNG。他们使用了非常不同的压缩技术,并且取决于图像的大小和内容,在各种情况下,一种可能比另一种更好。

You can experiment with different compression schemes by using JPEG versus PNG. They are using very different compression techniques and depending on the image size and content one can be better than the other in various situations.

我的2美分。.

这篇关于canvas.toDataURL(“ image / png”)-如何工作以及如何对其进行优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆