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)直接在這一行語句的上面一行打印信息)。沒報(bào)錯(cuò)你只能自己慢慢打斷點(diǎn)一個(gè)模塊一個(gè)模塊去排除。
相關(guān)文章:
1. golang - 用IDE看docker源碼時(shí)的小問題2. html - css氣泡,實(shí)現(xiàn)“倒三角(不知道算不算三角了)”可透明的。3. phpstudy8.1沒集成mysql-front4. java - 如何點(diǎn)擊按鈕,重新運(yùn)行(我是初學(xué)者)?5. 運(yùn)行python程序時(shí)出現(xiàn)“應(yīng)用程序發(fā)生異常”的內(nèi)存錯(cuò)誤?6. 我何時(shí)應(yīng)該在Java中使用JFrame.add(component)和JFrame.getContentPane()。add(component)7. 利用IPMI遠(yuǎn)程安裝centos報(bào)錯(cuò)!8. 前端 - @media query 使用出現(xiàn)的問題?9. html5和Flash對(duì)抗是什么情況?10. javascript - 請(qǐng)指條明路,angular的$event,在select中卻是undefined?

網(wǎng)公網(wǎng)安備