niklasvh / html2canvas

Screenshots with JavaScript
https://html2canvas.hertzen.com/
MIT License
30.09k stars 4.75k forks source link

Who can help answer why this is #3161

Closed jxh150535011 closed 3 weeks ago

jxh150535011 commented 3 months ago
    console.time('toDataURL');
    const base64 = canvas.toDataURL('image/png', 1.0);
    convertBase64UrlToBlob(base64);  // Removing this sentence is faster
    console.timeEnd('toDataURL');

    const blob: any = await new Promise(resolve => {
      console.time('toBlob');
      return canvas.toBlob((blob) => {
        console.timeEnd('toBlob');
        resolve(blob)
      }, 'image/png', 1.0)
    });

The above results show that the toBlob method does not have any advantages. On the contrary, removing the conversion code from toDataURL will result in a more significant improvement. If the execution order of toDataURL and toBlob is swapped, toDataURL will clearly have an advantage over toBlob (even if the conversion code is not removed). I have searched for a lot of content and many articles have pointed out that toBlob not only has advantages in memory and performance. But my test results do not support this conclusion, and often toDataURL performs better

Result of every hundred requests: toDataURL: 2978ms toBlob: 3040ms

cyfung1031 commented 1 month ago
toDataURL: Returns a Base64 encoded string.
toBlob: Returns a Blob object.
toDataURL can be slower and memory intensive for large images because Base64 encoding increases the size of the data by approximately 33%.
toBlob is typically more efficient for handling binary data directly.
Use toDataURL when you need to embed the image in HTML/CSS or send it as part of a text-based format.
Use toBlob when you need to upload the image to a server or perform operations on the binary data.

For the measurement, it is incorrect. You are comparing sync function and async function.

sync function can use all the resource and power to do the process async function would not

If you want to compare A and B. It must be apple to apple. orange to orange. don't compare sync function to async function.