首頁  >  問答  >  主體

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 天前807

全部回覆(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
  • 取消回覆