仅限Android浏览器:canvas.toDataURL抛出未捕获错误:SecurityError:DOM异常18

时间:2014-04-01 10:36:22

标签: javascript html5 canvas cross-domain android-browser

我正在尝试将图像转换为base64字符串,并将其作为源代码放入img标记中。图片存储在脚本的其他子域中。所以我把它放在我的.htaccess文件中以确保允许访问

<ifModule mod_headers.c>
  Header set Access-Control-Allow-Origin http://xxx.mydomain.com
  Header set Access-Control-Allow-Credentials true
</ifModule>

它在桌面浏览器,iOS上的Safari和Android上的Chrome上运行良好。但不是在Androids原生浏览器中。我进入控制台的所有内容都是

Uncaught Error: SecurityError: DOM Exception 18

知道为什么它在所有浏览器上工作但不在机器人上工作吗?这是我的剧本

function convertImgToBase64(url, callback, outputFormat){
    var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'),
        img = new Image;
    img.onload = function(){
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img,0,0);
        var dataURL = canvas.toDataURL(outputFormat || 'image/jpg');
        callback.call(this, dataURL);
        canvas = null;
    };
    img.crossOrigin = 'anonymous';
    img.src = url;
}

var imgString;

if (localStorage.getItem('xxxItemNamexxx')) {
    imgString = localStorage.getItem('xxxItemNamexxx');
} else {
    convertImgToBase64($('#my-picture').attr('src'), function(base64Img) {
        imgString = base64Img;
        localStorage.setItem('xxxItemNamexxx', base64Img);
    });
}

$('#my-picture').attr('src', imgString);

感谢您的任何意见!

1 个答案:

答案 0 :(得分:0)

我在android中有类似的问题,而this answer帮助了。

function convertImgToBase64(url, callback, outputFormat){
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);

  xhr.responseType = 'arraybuffer';

  xhr.onload = function(e) {
    if (xhr.status == 200) {
      var uInt8Array = new Uint8Array(xhr.response);
      var i = uInt8Array.length;
      var binaryString = new Array(i);
      while (i--) {
        binaryString[i] = String.fromCharCode(uInt8Array[i]);
      }
      var data = binaryString.join('');
      var base64 = window.btoa(data);
      var dataUrl = "data:" + (outputFormat || "image/png") + ";base64," + base64;
      callback.call(this, dataUrl);
    }
  };

  xhr.send();
}