Questions: 1. I don’t know why, canvasSometimes can’t get the drawing data, only “data:;”. Please tell me where I wrote this wrong. 2. When I write canvas like this, there is nothing that needs to be optimized
Related codes:
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的參數(shù)值是基于實際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();
});
}
擁有18年軟件開發(fā)和IT教學(xué)經(jīng)驗。曾任多家上市公司技術(shù)總監(jiān)、架構(gòu)師、項目經(jīng)理、高級軟件工程師等職務(wù)。 網(wǎng)絡(luò)人氣名人講師,...
The image is too large. Calling canvas.toDataURL
sometimes fails. It is recommended to compress the image before calling and see if this article can help you with file uploading
I often encounter this kind of thing, there are various reasons, usually the parameters are wrong, take a look
ctx.drawImage(img,opt.left,opt.top,imgW,imgH,0, 0,width,height);
Whether the parameters in this line have values ??(please print the information directly on the line above this line of statement).
If there is no error, you can only slowly interrupt one module one by one to eliminate it.