Home Web Front-end JS Tutorial Solutions to compatibility issues using canvas.toDataURL under IE11

Solutions to compatibility issues using canvas.toDataURL under IE11

Apr 14, 2018 pm 02:12 PM
ie11

This time I will bring you ideas for solving the compatibility problem of using canvas.toDataURL in IE11. What are the precautions?, the following is the actual combat Let’s take a look at the case.

problem found

Recently, the toDataURL method of canvas has been used in the project to obtain the base64 format data of the picture for uploading to the background. Since I have encountered the pitfall of canvas being contaminated by cross-domain images before and unable to obtain data, I cleverly added the crossOrigin attribute value from the beginning. The code is roughly as follows:

const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
const imageElement = document.createElement("img");
imageElement.crossOrigin = "Anonymous";
imageElement.onload = () => {
 context.drawImage(
 imageElement,
 params.left,
 params.top,
 canvas.width,
 canvas.height,
 0,
 0,
 canvas.width,
 canvas.height
 );
 const dataUrl = canvas.toDataURL("image/jpeg", 1);
}
imageElement.src = 'xxx';
Copy after login

I thought it was foolproof, and it went very smoothly on the Chrome browser; however, on IE11, an inexplicable SecurityError occurred:

Solutions to compatibility issues using canvas.toDataURL under IE11

There is no specific error message, only the line of executing toDataURL is located through the prompt, which is really confusing.

try

I Googled it for the first time and found that many people have encountered this problem, but did not see any effective solution. Some people suggested using Fabric.js, but after looking at it, I thought it was too troublesome. On caniuse, it is also clearly marked that this method has problems on IE11.

It seemed to be a bug on IE, so I thought of a way to save the country: there is not only one way to obtain the base64 data of the image. Since the toDataURL method is not well supported, then use another method:

  • First convert canvas to blob

  • Then use FileReader to read in the form of dataUrl

The code is roughly as follows:

const reader = new FileReader();
reader.readAsDataURL(canvas.msToBlob());
reader.onloadend = () => {
 const base64data = reader.result;
};
Copy after login

However, this is of no use....

This time it was the msToBlob method's turn to report a SecurityError. I:? ? ?

solve

It seems that it may really be a security reason. The only security reason is cross-domain images. I was thinking that maybe the security policy on IE is stricter, even if crossOrigin = "Anonymous" is set, the data is still not allowed to be read, so I thought of another idea. Since it is cross-domain, then cross-domain factors should be removed. Remove:

  • Use ajax to request the binary data of the image

  • # Convert binary data to base64 format

  • Set the obtained base64 data as the src of the picture element and draw it to the canvas

  • Normally call toDataURL

The code is roughly as follows:

// 之前的代码
// ...
// 最后一行 imageElement.src = 'xxx' 替换:
getDataUrlBySrc('xxx').then(b64 => (imageElement.src = b64));
function getDataUrlBySrc(src: string) {
 return new Promise<string>((resolve, reject) => {
 if (Cache.localGet("isIE")) {
  const xmlHTTP = new XMLHttpRequest();
  xmlHTTP.open("GET", src, true);
  // 以 ArrayBuffer 的形式返回数据
  xmlHTTP.responseType = "arraybuffer";
  xmlHTTP.onload = function(e) {
  
  // 1. 将返回的数据存储在一个 8 位无符号整数值的类型化数组里面
  const arr = new Uint8Array(xmlHTTP.response);
  
  // 2. 转为 charCode 字符串
  const raw = Array.prototype.map
   .call(arr, charCode => String.fromCharCode(charCode))
   .join("");
   
  // 3. 将二进制字符串转为 base64 编码的字符串
  const b64 = btoa(raw);
  
  const dataURL = "data:image/jpeg;base64," + b64;
  resolve(dataURL);
  };
  xmlHTTP.onerror = function(err) {
  reject(err);
  };
  xmlHTTP.send();
 } else {
  resolve(src);
 }
 });
}</string>
Copy after login

Tried it and successfully achieved the goal.

Later, I checked the information and learned that if the canvas is contaminated, neither toDataURL nor toBlob will be executed successfully.

defect

Although this method can achieve the goal, it sacrifices performance. Not only do you need to request the image data first, the conversion of the data encoding is also quite time-consuming. Small pictures are okay, but if the pictures are larger, for example, more than 3M, the whole process can take up to one or two minutes, which is unacceptable.

Will the toDataUrl of canvas compress the image?

When using the drawImage method of canvas to draw an image object onto the canvas, the image size will increase significantly and can only be saved in PNG format.

Convert the canvas to base64 using toDataUrl. Even if encoderOptions is set to 1, the image will be greatly reduced, but it will still be larger than the original image. If encoderOptions uses the default 0.92, the final image size will be similar to the initial one

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

How to use Angular4 input and output

How to implement dynamic cascade loading of easyui's drop-down box (with code)

The above is the detailed content of Solutions to compatibility issues using canvas.toDataURL under IE11. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles