在Chrome中使用toDataURL有其他选择吗

Are there any alternatives for using toDataURL in Chrome?

本文关键字:其他 选择 toDataURL Chrome      更新时间:2023-09-26

主要问题是我必须处理许多图像。我不能对所有这些都使用crossOrigin属性。

My code looks like this:
<script>
var c=document.getElementById('example');
var ctx=c.getContext('2d');
var LeftHand = new Image();
LeftHand.id="imq1";
var RightHand = new Image();
RightHand.id="imq2";
var Body = new Image();
Body.id="imq6";
boyBody.src = "https://getout-s3.s3.amazonaws.com/baseBody/boy-02.png";
LeftHand.src = "https://getout-s3.s3.amazonaws.com/NK4XtQvkZ4MGctZf_.hand(unisex)_13.png ";
RightHand.src = "https://getout-s3.s3.amazonaws.com/OPdFPcU2sORgNmTy_.hand(unisex)_9.png ";
Body.src = "https://getout-s3.s3.amazonaws.com/HRZqrTYSdJXGedgX_.Body_(m)7.png ";
boyBody.onload = function() {
ctx.drawImage(boyBody, 0, 0, boyBody.width/2, boyBody.height/2);
ctx.drawImage(LeftHand, (899 - LeftHand.width/2)/2, (867 - LeftHand.height/2)/2, LeftHand.width/2, LeftHand.height/2);
ctx.drawImage(Underwear, (599 - Underwear.width/2)/2, (845 - Underwear.height/2)/2, Underwear.width/2, Underwear.height/2);
ctx.drawImage(Body, (599 - Body.width/2)/2, (557 - Body.height/2)/2, Body.width/2, Body.height/2);
var img = c.toDataURL("image/png");
document.write('<img src="' + img + '" />');
};
</script>

浏览器不允许程序员导出跨域内容,这是出于非常好的安全原因。你的私人银行信息是跨域内容,你不想把它作为导出设备提供给小偷。

因此,在画布上绘制跨域图像后,context.toDataURL会立即被禁用。context.getImageData的禁用也是如此。(context.getImageData是导出画布内容的另一种方法)。

要允许将画布内容导出给用户,您必须将所有图像托管在与网页相同的域中

顺便说一句,在绘制所有元素之前,必须给它们加载的时间。这里有一个图像加载器,它可以提前加载所有图像,然后在所有图像完全加载时调用start()。将ctx.drawImage放入start()。

// put the paths to your images in imageURLs[]
var imageURLs=[];  
imageURLs.push("https://getout-s3.s3.amazonaws.com/baseBody/boy-02.png");
imageURLs.push("https://getout-s3.s3.amazonaws.com/NK4XtQvkZ4MGctZf_.hand(unisex)_13.png");
// ...etc, for all images
// the loaded images will be placed in imgs[]
var imgs=[];
var imagesOK=0;
loadAllImages(start);
function loadAllImages(callback){
    for (var i=0; i<imageURLs.length; i++) {
        var img = new Image();
        imgs.push(img);
        img.onload = function(){ 
            imagesOK++; 
            if (imagesOK>=imageURLs.length ) {
                callback();
            }
        };
        img.onerror=function(){alert("image load failed");} 
        img.crossOrigin="anonymous";
        img.src = imageURLs[i];
    }      
}
function start(){
    // the imgs[] array now holds fully loaded images
    // the imgs[] are in the same order as imageURLs[]
}