精华内容
下载资源
问答
  • toDataURL returning nothing

    2020-12-02 19:17:19
    <p>You select the image, crop but the images are not being loaded as the base64 representation of the crop is not being return by <code>toDataURL</code></p>该提问来源于开源项目:Norserium/vue-...
  • <p>When I use toDataURL on iOS and console.log the result, the <code>data:image/png;base64,</code> part is missing and doing the following doesn't work: <pre><code> const mapImg = document....
  • Add support for toDataURL

    2020-12-09 07:18:49
    <div><p>This fixes an issue I was having using this library, where we call <code>canvas.toDataURL</code> in one of our react components. <p>I've used an empty string, but we can optionally go for ...
  • <p>When I attempt to render a hidden SVG using toDataURL I fairly consistently end up with an java.lang.IndexOutOfBoundsException. However, I do not encounter it at the same index consistently. <p>I ...
  • 出现Canvas.toDataURL 图片跨域问题怎么解决呢?下面小编就为大家带来一篇Canvas.toDataURL 图片跨域问题的快速解决方法。一起跟随小编过来看看吧
  • 报错详尽信息Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.关键词canvas.toDataURL()crossOriginAccess-Control-Allow-Origin前言最近在做...

    报错详尽信息

    Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

    关键词

    canvas.toDataURL()

    crossOrigin

    Access-Control-Allow-Origin

    前言

    最近在做一个创意类的图片合成工具,大概齐就是通过拼接自定义的文字和图片信息生成一张商品图片类似的功能,项目中用到了fabric.js这个画板库,最后一步在保存图片的时候报上面的一长串错误,墙内墙外搜了一遍,给出的解决方案都不全面,为避免同学们再次踩坑,于是有了此文

    正文

    我们在convertDOM2Image时,如果DOM内存在图片资源,该资源所在的web-server是不支持跨域的,保存图片是不会成功的。

    因此在排查问题时,首先要确定

    web-server是否允许跨域,我们以nginx为例,response-header内要存在Access-Control-Allow-Orgin:xxxx(可以是*,安全性要求比较高的可以根据主域名自定义)

    如果是img标签, 是否添加了crossorigin="anonymous", 如果是Image对象,同样是否添加了改属性obj.crossOrigin='anonymouse'

    如果还不行,这里先不把答案放出来,我们先看看栗子

    在接下来的栗子中我们会用到将Image转换为canvas对象的方法

    function convertImageToCanvas(image) {

    // 创建canvas DOM元素,并设置其宽高和图片一样

    let canvas = document.createElement("canvas");

    canvas.width = image.width;

    canvas.height = image.height;

    canvas.getContext("2d").drawImage(image, 0, 0);

    // 我们在实际的开发中,需要将抓换后的base64图片编码传输到后台图片服务器,由server直接存储或者生成一张图片;

    // 所以会用到 toDataURL

    console.log(canvas.toDataURL('image/jpeg'))

    return canvas;

    }

    栗子1

    本地未设置跨域允许选项crossorigin=anonymous,web-server未设置跨域允许选项

    本地未设置跨域允许选项crossorigin=anonymous,web-server未设置跨域允许选项

    canvas保存

    function setCanvas(DOMID) {

    let img = document.getElementById(DOMID).querySelector('img')

    document.body.appendChild(convertImageToCanvas(img))

    }

    很显然,报错

    栗子2

    本地标签内设置跨域允许选项, web-server未设置跨域允许选项

    这次连图片都出不来,直接报错

    这个好理解,浏览器同源策略限制嘛

    Access to image at 'xxxx' (redirected from 'xxxx') from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

    栗子3

    本地未设置跨域允许选项crossorigin=anonymous, web-server设置跨域允许选项

    报错,妥妥的。

    栗子4

    本地标签内设置跨域允许选项crossorigin=anonymous, web-server设置跨域允许选项

    本地设置跨域允许选项`crossorigin=anonymous`,`web-server`设置跨域允许选项

    canvas保存

    居然可以了,但是~如果在代码内设置跨域呢?

    栗子5

    function setCanvas(DOMID) {

    let img = document.getElementById(DOMID).querySelector('img')

    img.crossOrigin= 'anonymous'

    document.body.appendChild(convertImageToCanvas(img))

    }

    报错

    我看官方文档的意思是必须同步设置crossOrigin=anonymouse,该图片凭证才会被信任

    This means that CORS is enabled and credentials are sent if the image is fetched from the same origin from which the document was loaded.

    否则缓存的图像数据仍然会被画布视为有污染的跨源内容.

    怎么办?重新取一遍图片呗,加个随机数,图片还是那个图片,不过加了个马甲,浏览器就不认识了

    栗子6

    function setCanvas(DOMID) {

    let img = document.getElementById(DOMID).querySelector('img')

    img.src =img.src+'?v='+Math.random()

    img.crossOrigin= 'anonymous'

    img.οnlοad=()=>{

    document.body.appendChild(convertImageToCanvas(img))

    }

    }

    binggo, 完美解决

    所以我们在开发过程中,新建图片,更换图片,还原图片等功能代码内,最好每一次都加个随机数,以保证源都是最新的,不走缓存

    多说一点吧,关于fabric.js的相关跨域配置见下方

    let _fabricConfig = {

    // ....

    crossOrigin:'anonymous'

    };

    /* fabric对象 */

    let _fabricObj = new fabric.Canvas(id, _fabricConfig);

    // 新建图片对象时

    let imgInstance = new fabric.Image.fromURL(url + '?v='+ Math.random(), img => {}, {crossOrigin: 'anonymous'})

    // 动态更新图片时

    let currentActive = _fabricInstance.getActiveObj();

    currentActive.setSrc(randomURL, img =>{}, {crossOrigin: 'anonymous'})

    展开全文
  • <div><p>The call to <code>canvas.toDataURL()</code> omits the second parameter for controlling the image quality: <p>...
  • <ul><li>[x] monkey patch toBlob</li><li>[x] monkey patch toDataURL</li><li>[x] increase test coverage of prototype mocking functions to 100%</li><li>[x] move mock functions to their own folder</li><li...
  • <div><p>Assuming I will to initialize the cropper with some image URL and I want to be able to edit it (meaning to crop the image and call canvas.toDataURL based on the cropped image). The problem is,...
  • await this.groupRef.toDataURL({ mimeType: "image/jpeg", x, y, width: scaledImgWidth, height: scaledImgHeight, quality: 1, pixelRatio: this.pixelRatio }); if (!dataURL) { this.props...
  • Is it possible to get the image from the canvas using toDataURL? I know generally how to use toDataURL, but the problem is the canvas generated in your script has no id so I don't know how to ...
  • 主要介绍了详解如何解决canvas图片getImageData,toDataURL跨域问题,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
  • canvas的toDataURL()方法

    千次阅读 热门讨论 2020-06-14 23:16:29
    canvas的toDataURL()方法是返回一个包含图片展示的 数据URL。可以使用type参数其类型,默认为PNG格式。图片的分辨率为96dpi。 一、语法 canvas.toDataURL(type, encoderOptions); 二、参数 1、type:图片格式,...

    canvas的toDataURL()方法是返回一个包含图片展示的 数据URL。可以使用 type 参数其类型,默认为 PNG 格式。图片的分辨率为96dpi。

    一、语法

    canvas.toDataURL(type, encoderOptions);

    二、参数

    1、type:图片格式,默认为 image/png,可以是其他image/jpeg等

    2、encoderOptions:0到1之间的取值,主要用来选定图片的质量,默认值是0.92,超出范围也会选择默认值。

    三、返回值

    返回值是一个数据url,是base64组成的图片的源数据、可以直接赋值给图片的src属性。

    <!DOCTYPE html>
    <html class="no-js">
    
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">
    </head>
    
    <body>
        <canvas id="mycanvas" width="200" height="200"></canvas>
        <img src="" id="myImage">
        <script type="text/javascript">
            var cvs = document.getElementById('mycanvas'),
                ctx = cvs.getContext('2d'),
                img = document.getElementById('myImage');
            ctx.fillStyle = "yellow";
            ctx.fillRect(0, 0, 300, 400);
            var imgDataSrc = cvs.toDataURL('image/png');
            img.src = imgDataSrc;
        </script>
    </body>
    
    </html>

    注意:(是借鉴MDN的)

    1、如果画布的高度或宽度是0,那么会返回字符串“data:,”。

    2、如果传入的类型非“image/png”,但是返回的值以“data:image/png”开头,那么该传入的类型是不支持的(没遇到)

    3、Chrome支持“image/webp”类型。

    展开全文
  • 下面小编就为大家带来一篇canvas.toDataURL('image/png')报错处理方法推荐。小编觉得挺不错的,现在分享给大家,也给大家做个参考,一起跟随小编过来看看吧
  • 现象:在使用canvas的toDataURL()方法时,控制台有时会报错:Uncaught DOMException: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported. 原因:这是由于之前由...

    现象:在使用canvas的toDataURL()方法时,控制台有时会报错:Uncaught DOMException: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported.
    原因:这是由于之前由drawImage()向canvas导入的图片跨域而导致的。
    解决方法:

    1、在引用图片之前打开跨域资源允许权限(一定要注意顺序):

    var img=new Image;
    img.setAttribute('crossOrigin', 'anonymous') //关键
    img.src = url + '?time=' + new Date().valueOf();
    img.src="图片地址";
    

    2、存放图片地址的服务器也要开启跨域允许权限,不然会报错:No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

    如Apache设置:
    ①.打开LoadModule headers_module modules/mod_headers.so

    ②.在虚拟主机内加上 Header set Access-Control-Allow-Origin *

    总结

    跨域图片能正常裁剪(图片未转化成base64),应该满足三个条件:

    1,img元素中设置crossorigin属性
    2,图片允许跨域,设置响应头Access-Control-Allow-Origin
    3,使用js方式请求图片资源, 需要避免使用缓存,设置url后加上时间戳,或者http头设置Cache-Control为no-cache

    最后 贴上我canvas绘制图片,画线最后生成图片的代码

    在这里插入图片描述

    <div class="jiepingCanvas" id="jtCs"  v-show="dialogJPG">
        <canvas id="mycanvas" ref="mycanvas" width="848" height="508"></canvas>
        <div class="yesNo">
            <div class="jtYes" @click="jtSure()">
                <img src="../common/comImg/yes.png" alt="">
            </div>
            <div class="jtYes" @click="jtCancel()">
                <img src="../common/comImg/no.png" alt="">
            </div>
        </div>
        <div class="tipsjt">
             提示:图片可以进行画线操作
        </div>
    </div>
    
    data() {
     return {
    	 onoffjt:false,
    	 oldxjt:0,
    	 oldyjt:0,
    	 ctxjt:'',
    	 linecolorjt:'',
    	 linwjt:8,
    	 onArrjt:[],
    	 endArrjt:[],
    	 ctxjt:"",
    	 huajt:false,
    	 canvasJT:""
     }
    }
    
    //初始化画布
    canvasInit(){
    	var that=this
    	var imgUrl='https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2583035764,1571388243&fm=26&gp=0.jpg'
    	that.dialogJPG=true
    	//  获取canvas
    	that.canvasJT = document.getElementById("mycanvas")
    	var a = setInterval(() =>{
    	    that.canvasJT = document.getElementById("mycanvas")
    	    if(!that.canvasJT){
    	        return false
    	    } else {
    	        clearInterval(a)
    	        that.ctxjt = that.canvasJT.getContext('2d')
    	        var img = new Image()
    	        
    	        img.src = imgUrl+"?timeStamp="+new Date();
    	        img.setAttribute("crossOrigin",'anonymous')
    	        img.onload = function(){
    	            if(img.complete){
    	                //  根据图像重新设定了canvas的长宽
    	                that.canvasJT.setAttribute("width",844)
    	                that.canvasJT.setAttribute("height",504)
    	                //  绘制图片
    	                that.ctxjt.drawImage(img,0,0,844,504)
    	                that.initjt()
    	            }
    	        }
    	        that.dialogJPG=true
    	    }
    	},1)
    }
    
    //开始画线
    initjt(){
        //画一个黑色矩形
        this.ctxjt.fillStyle="transparent";
        this.ctxjt.fillRect(0,0,848,508);
        //按下标记
        this.onoffjt=false;
        this.oldxjt=0;
        this.oldyjt=0;
        this.linecolorjt=this.linecolor;
        //宽度默认为8
        this.linwjt=8;
        //鼠标移动事件,事件绑定
        this.canvasJT.addEventListener("mousemove",this.drawjt,true);
        this.canvasJT.addEventListener("mousedown",this.downjt,false);
        this.canvasJT.addEventListener("mouseup",this.upjt,false);
    },
    //鼠标按下事件
    downjt(event){
        if(this.huajt==true){
            this.onoffjt=false
        }else{
            this.onoffjt=true;
            this.oldxjt=event.pageX-this.canvasJT.getBoundingClientRect().left;
            this.oldyjt=event.pageY-this.canvasJT.getBoundingClientRect().top;
            console.log(this.oldxjt,this.oldyjt,'event')
        }
    },
    //鼠标绘制线条
    drawjt(event){
        if(this.onoffjt==true){
                    var newxjt=event.pageX-this.canvasJT.getBoundingClientRect().left;
                    //getBoundingClientRect方法是边框距离浏览器的距离
                    var newyjt=event.pageY-this.canvasJT.getBoundingClientRect().top;
                    // console.log(newx,newy,'000')
                    this.ctxjt.beginPath();
                    this.ctxjt.moveTo(this.oldxjt,this.oldyjt);
                    this.ctxjt.lineTo(newxjt,newyjt);
                    // console.log(newx);
                    this.ctxjt.strokeStyle=this.linecolorjt;
                    this.ctxjt.lineWidth=this.linwjt;
                    this.ctxjt.lineCap="round";
                    this.ctxjt.stroke();
                    
                    this.oldxjt=newxjt;
                    this.oldyjt=newyjt;
                    let xy={
                        x:this.oldxjt,
                        y:this.oldyjt
                    }
                    this.onArrjt.push(xy)
                }
           
    },
    //鼠标抬起事件
    upjt(){
        this.onoffjt=false;
        if(this.onArrjt.length>0){
            this.endArrjt.push(this.onArrjt)
            this.onArrjt=[]
        }
    },
    //点击确认生成图片
    jtSure(){
        let dataURL = document.getElementById('mycanvas')
        let dataURLs=dataURL.toDataURL("images/png")
            let params = {
                data: dataURLs,
                compid: 30,
                hzm:'png'
            };
            postUpFile(params).then(res => {
                let { ReturnCode, Data } = res;
                if (ReturnCode == 200) {
    
                    let DataUrl = Data.Url;
                    console.log(DataUrl,'DataUrl路径')
                    
                    let msg=this.nickName+'#&$'+DataUrl
                    let senBtnws={
                        order:enumPack.enum_msg.drawImage,
                        uid:Number(this.option.uid),
                        msg:msg,
                        device:4
                    }
                    this.handdleMsg(JSON.stringify(senBtnws))
                    this.stepArray.push(DataUrl)
    
                } 
    
            });
    
            this.dialogJPG=false
            let c=document.getElementById("mycanvas");  
            let cxtjt=c.getContext("2d");  
            cxtjt.clearRect(0,0,c.width,c.height); 
    },
    //点击取消清除画布
    jtCancel(){
        this.dialogJPG=false
        let c=document.getElementById("mycanvas");  
        let cxtjt=c.getContext("2d");  
        cxtjt.clearRect(0,0,c.width,c.height); 
    }
    }
    
    

    以上参考了很多大神的文章
    如:https://www.cnblogs.com/sunala/p/7085525.html https://segmentfault.com/q/1010000008648867

    展开全文
  • typeof null,toDataURL

    2018-07-23 06:09:23
    typeof null // object toDataURL // canvas把canvas转化为base64,base64可以作为img的src 复制代码 转载于:https://juejin.im/post/5b514c346fb9a04fa42fb1a6
    typeof null // object   
    toDataURL // canvas把canvas转化为base64,base64可以作为img的src 复制代码

    转载于:https://juejin.im/post/5b514c346fb9a04fa42fb1a6

    展开全文
  • 最近做了一个海报生成的组件,需要drawimage到画布上,image来源包括本地和异地的图片src...首先讲一点,异地图片如果不设置允许跨域访问,canvas.toDataURL是无法画image的,报画布污染的错;首先放一张我要生成的图;
  • <div><p>hi, signature_pad's toDataURL has two option parameters imageType and quality</p><p>该提问来源于开源项目:wulfsolter/angular2-signaturepad</p></div>
  • 在安卓手机的微信浏览器上出现stack: "Error: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported 最初解决方法(在安卓的微信浏览器上有问题) let image = new ...
  • canvas的toDataURL方法

    2017-09-28 09:43:00
    前一阵七夕前夕搞了一个微信活动,共享男女友,时间紧任务重,记得当时是周三提的需求,那就抓紧搞起来,后来会有一个生成图片的功能,遇到了一些坎,下面分析下技术点,用到的就是canvas的toDataURL()方法,可是...
  • <div><p>We are using <code>toDataURL()</code> when the map should move similar to #50. However, the generated image is of bad quality. For testing, we removed the following lines in the <code>...
  • <p>stage.toDataURL({ callback: function (dataUrl) { alert(dataUrl) }, error:function(er) { alert(er) } });</p><p>该提问来源于开源项目:ericdrowell/KineticJS</p></div>
  • 将HTML5 Canvas的内容保存为图片主要思想是借助Canvas自己的API - toDataURL()来实现,具体实现如下,感兴趣的朋友可以参考下哈,希望对你有所帮助
  • <div><p>toDataURL is working on iOS but crashing on Android. <p><strong>RN version :</strong> 0.47.0 <strong>react-native-svg version :</strong> 5.4.1 <strong>react version :</strong> 16.0.0-alpha.12...
  • 解决Canvas.toDataURL 图片跨域问题
  • 记录一下toDataURL的坑

    2020-06-01 15:55:28
    Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’ 项目中有个需求,将当前页面的部分内容做成pdf导出,于是使用了JsPDF和html2Canvas,然而发现导出的时候报了一行错误 查阅发现是跨域的问题,但其实是自己在...
  • Uncaught DOMException: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported. 关键词 canvas.toDataURL() crossOrigin Access-Control-Allow-Origin 前言 最近在...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,421
精华内容 568
热门标签
关键字:

todataurl