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. mysql 查詢身份證號字段值有效的數據2. python - 爬蟲模擬登錄后,爬取csdn后臺文章列表遇到的問題3. mysql - 把一個表中的數據count更新到另一個表里?4. javascript - 彈出一個子窗口,操作之后關閉,主窗口會得到相應的響應,例如網站的某些登錄界面,django后臺的管理等,這是怎么實現的呢?5. 視頻文件不能播放,怎么辦?6. 請教使用PDO連接MSSQL數據庫插入是亂碼問題?7. mysql - 分庫分表、分區、讀寫分離 這些都是用在什么場景下 ,會帶來哪些效率或者其他方面的好處8. python bottle跑起來以后,定時執行的任務為什么每次都重復(多)執行一次?9. android - 分享到微信,如何快速轉換成字節數組10. visual-studio - Python OpenCV: 奇怪的自動補全問題
