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(); });}
問題解答
回答1:圖片過大,調用canvas.toDataURL有時候會失敗的,建議調用之前先對圖片做壓縮處理,看看這篇文章能否幫到你文件上傳那些事兒
回答2:我經常碰到這樣的事,各種各樣的原因都有,一般都是參數什么的不對,你看看ctx.drawImage(img,opt.left,opt.top,imgW,imgH,0,0,width,height);這一行的里面的參數是否都有值(請直接在這一行語句的上面一行打印信息)。沒報錯你只能自己慢慢打斷點一個模塊一個模塊去排除。
相關文章:
1. javascript - node.js promise沒用2. golang - 用IDE看docker源碼時的小問題3. yii2中restful配置好后在nginx下報404錯誤4. 算法 - python 給定一個正整數a和一個包含任意個正整數的 列表 b,求所有<=a 的加法組合5. android 如何實現如圖中的鍵盤上的公式及edittext的內容展示呢6. java - 我在用Struts2上傳文件時,報以下錯誤怎么回事?7. c++ - 如何正確的使用QWebEngineView?8. PHP注冊功能9. mysql - 求SQL語句10. MySQL如何實現表中再嵌套一個表?
