html5 - canvas有时候会拿不到toDataURL数据

查看:723
本文介绍了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();
                    });
        }

解决方案

目前没有遇到和canvas有关的问题,引起这个问题是在与我去获取Dom元素img的信息,img onload要比渲染的快,所以没能拿到宽高。失误失误

这篇关于html5 - canvas有时候会拿不到toDataURL数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆