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. java - 关于京东单点登录认证的问题2. python - 用urllib抓取网页上的下载链接,目标文件是xls形式,但发现抓下来的xls是空表,里面只有一句报错信息,求帮助。3. 怎样用python给mp3添加封面?4. 网页爬虫 - python 爬虫怎么处理json内容5. android - 手机qq浏览器处理服务器端返回的数据时,数据格式有时为object有时为string是什么原因?6. 利用百度地图API定位及附件商家信息服务7. 怎么能做出标签切换页的效果,(文字内容随动)8. win10 python3.5 matplotlib使用报错9. (python)关于如何做到按win+R再输入文件文件名就可以运行?10. python - 图片爬虫时候遇到问题 urllib.request.urlretrieve 下载到指定文件夹不成功?

网公网安备