首页  >  问答  >  正文

html5 - canvas有时候会拿不到toDataURL数据

问题:1.不知道为什么,canvas有时候会拿不到绘图数据,只拿到了“data:;” 。请问我这么写错在哪里。2.我这么写canvas 哪里需要优化的没有

相关代码:

        initCanvas:function(opt){
            var self=this;
            var img=new Image();
            var ctx,type=opt?2:1;

            img.setAttribute('crossOrigin', 'anonymous');
            img.onload=function(){
                var $img=self._view._cropBlock.find('img');
                var sizes,ratio;
                var imgW=img.width;//要截取的图片(引用的图片)宽度
                var imgH=img.height;
                console.log('img',imgW,imgH);
                if(!opt){
                    sizes=self.getCanvasSize($img);
                    opt={
                        left:0,
                        top:0,
                        width:sizes.width,//画布的宽度
                        height:sizes.height//画布的高度
                    };
                    ratio=Number((opt.width/img.width).toFixed(2));
                }else{

                    ratio=Number(($img.width()/img.width).toFixed(2))-0.01;//实际img元素和图片实际比例,四舍五入需减0.01
                    opt.left=opt.left/ratio;//opt的参数值是基于实际img元素的,要获得基于实际图片的值
                    opt.top=opt.top/ratio;
                    imgW=opt.width/ratio;
                    imgH=opt.height/ratio;
                }
                self.canvas = document.createElement('canvas');
                $.extend(self.canvas,{width:opt.width,height:opt.height});

                ctx = self.canvas.getContext('2d');
                ctx.save();
                var width=self.canvas.width||400;
                var height=self.canvas.height||400;console.log(self.canvas,width,height);
                ctx.clearRect(0,0,width,height);
                ctx.drawImage(img,opt.left,opt.top,imgW,imgH,0,0,width,height);
                ctx.restore();

                self.getSearchList(self.canvas,{imgUrl:img.src,type:type});
                self.canvas.remove();
            };
            img.onerror=function(err){
                console.log('canvas error:'+err);
            };
            img.src=this._model.currentImg;
        },
        getSearchList:function(canvas,opt,callback){
            var self=this;
            var url=canvas.toDataURL("image/jpeg",0.2);
            $.extend(opt,{imgUrlBase64:url});

            callback=callback|| $.noop;
            common.services.getRecognizedResultList(opt)
                    .success(function(data){
                        self.searchList=data.results;
                        callback();
                    });
        }
高洛峰高洛峰2666 天前803

全部回复(2)我来回复

  • 为情所困

    为情所困2017-06-06 09:55:01

    图片过大,调用canvas.toDataURL有时候会失败的,建议调用之前先对图片做压缩处理,看看这篇文章能否帮到你文件上传那些事儿

    回复
    0
  • 伊谢尔伦

    伊谢尔伦2017-06-06 09:55:01

    我经常碰到这样的事,各种各样的原因都有,一般都是参数什么的不对,你看看
    ctx.drawImage(img,opt.left,opt.top,imgW,imgH,0,0,width,height);
    这一行的里面的参数是否都有值(请直接在这一行语句的上面一行打印信息)。
    没报错你只能自己慢慢打断点一个模块一个模块去排除。

    回复
    0
  • 取消回复