html5 - canvas有時(shí)候會(huì)拿不到toDataURL數(shù)據(jù)
問(wèn)題描述
問(wèn)題:1.不知道為什么,canvas有時(shí)候會(huì)拿不到繪圖數(shù)據(jù),只拿到了“data:;” 。請(qǐng)問(wèn)我這么寫錯(cuò)在哪里。2.我這么寫canvas 哪里需要優(yōu)化的沒(méi)有
相關(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(); });}
問(wèn)題解答
回答1:圖片過(guò)大,調(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ǔ)句的上面一行打印信息)。沒(méi)報(bào)錯(cuò)你只能自己慢慢打斷點(diǎn)一個(gè)模塊一個(gè)模塊去排除。
相關(guān)文章:
1. mysql - 一個(gè)表和多個(gè)表是多對(duì)多的關(guān)系,該怎么設(shè)計(jì)2. python 如何實(shí)現(xiàn)PHP替換圖片 鏈接3. html5 - iOS的webview加載出來(lái)的H5網(wǎng)頁(yè),怎么修改html標(biāo)簽select的樣式字體?4. 一個(gè)mysql聯(lián)表查詢的問(wèn)題5. python如何不改動(dòng)文件的情況下修改文件的 修改日期6. javascript - git clone 下來(lái)的項(xiàng)目 想在本地運(yùn)行 npm run install 報(bào)錯(cuò)7. mysql主從 - 請(qǐng)教下mysql 主動(dòng)-被動(dòng)模式的雙主配置 和 主從配置在應(yīng)用上有什么區(qū)別?8. angular.js - 三大框架react、vue、angular的分析9. python - django 里自定義的 login 方法,如何使用 login_required()10. 主從備份 - 跪求mysql 高可用主從方案
