html5 - canvas有時(shí)候會(huì)拿不到toDataURL數(shù)據(jù)
問題描述
問題:1.不知道為什么,canvas有時(shí)候會(huì)拿不到繪圖數(shù)據(jù),只拿到了“data:;” 。請(qǐng)問我這么寫錯(cuò)在哪里。2.我這么寫canvas 哪里需要優(yōu)化的沒有
相關(guān)代碼:
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;//實(shí)際img元素和圖片實(shí)際比例,四舍五入需減0.01 opt.left=opt.left/ratio;//opt的參數(shù)值是基于實(shí)際img元素的,要獲得基于實(shí)際圖片的值 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:圖片過大,調(diào)用canvas.toDataURL有時(shí)候會(huì)失敗的,建議調(diào)用之前先對(duì)圖片做壓縮處理,看看這篇文章能否幫到你文件上傳那些事兒
回答2:我經(jīng)常碰到這樣的事,各種各樣的原因都有,一般都是參數(shù)什么的不對(duì),你看看ctx.drawImage(img,opt.left,opt.top,imgW,imgH,0,0,width,height);這一行的里面的參數(shù)是否都有值(請(qǐng)直接在這一行語(yǔ)句的上面一行打印信息)。沒報(bào)錯(cuò)你只能自己慢慢打斷點(diǎn)一個(gè)模塊一個(gè)模塊去排除。
相關(guān)文章:
1. python - scrapy 如何組合2個(gè)不同頁(yè)面的數(shù)據(jù),一并存儲(chǔ)2. mysql優(yōu)化 - mysql 一張表如果不能確保字段列長(zhǎng)度一致,是不是就不需要用到char。3. node.js - mysql如何通過knex查詢今天和七天內(nèi)的匯總數(shù)據(jù)4. javascript - 用jsonp抓取qq音樂總是說回調(diào)函數(shù)沒有定義5. javascript - 新浪微博網(wǎng)頁(yè)版的字?jǐn)?shù)限制是怎么做的6. sublime可以用其他編譯器替換嗎?7. python2.7 - python 函數(shù)或者類 代碼的執(zhí)行順序8. 使用python中的pandas求每個(gè)值占該列的比例9. python - 多態(tài)調(diào)用方法時(shí)卻顯示bound method...10. mysql 怎么做到update只更新一行數(shù)據(jù)?
