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

Solutions to compatibility issues using canvas.toDataURL under IE11

php中世界最好的语言
php中世界最好的语言Original
2018-04-14 14:12:506689browse

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';

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;
};

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>

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:
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