首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Chrome中使用toDataURL有其他选择吗?

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

Stack Overflow用户
提问于 2015-02-09 15:45:18
回答 1查看 1K关注 0票数 0

主要的问题是,我必须处理许多图像。而且我不能对它们都使用crossOrigin属性。

代码语言:javascript
复制
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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-09 16:17:04

出于非常好的安全原因,浏览器不允许程序员输出跨域内容。您的私人银行信息是跨域内容,您不想提供给盗贼使用画布作为出口设备。

因此,在将跨域图像放到画布上后,context.toDataURL立即被禁用。对于context.getImageData,同样的禁用也是如此。(context.getImageData是导出画布内容的另一种方式)。

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

顺便说一句,在绘制元素之前,您必须给所有的元素加载时间。下面是一个图像加载器,它预先加载所有图像,然后在所有图像完全加载时调用start()。将ctx.drag图像放在start()中。

代码语言:javascript
复制
// 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[]

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28413591

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档