技术文档

canvas+图片 操作与转换

2017-03-14  本文已影响146人  AnneyLiu

加载图像到canvas画布中

var canvas = document.getElementById("mycanvas");

var context = canvas.getContext('2d');

var img =new Image();

img.onload =function(){

  context.drawImage(img,0,0,img.width,img.height);

}

img.src =YourImgUrl;

图片转成64base

function getBase64Image(img) {

var canvas = document.createElement("canvas");

canvas.width = img.width;

canvas.height = img.height;

var ctx = canvas.getContext("2d");

ctx.drawImage(img,0,0,img.width,img.height);

var dataURL = canvas.toDataURL("image/png");

return dataURL;

}

图片路径转换成base64

function convertImgToBase64(url,callback,outputFormat) {

var canvas = document.createElement('CANVAS'),

ctx = canvas.getContext('2d'),

img =new Image();

img.crossOrigin ='Anonymous';    //可解决跨域图片不能转换问题,或者img.crossOrigin = '';

img.onload =function() {

canvas.height = img.height;

canvas.width = img.width;

ctx.drawImage(img,0,0);

var dataURL = canvas.toDataURL(outputFormat ||'image/png');

callback.call(this,dataURL);

canvas =null;

};

img.src = url;

}

图片缓存

function cacheExternalImage(url){

var img =new Image(),   

src = url,   

cvs =document.createElement('canvas'),    

ctx = cvs.getContext('2d');   

img.crossOrigin ="Anonymous";    

img.onload =function(){

//ctx.drawImage( img, 0, 0 );

}    

img.src = src;

if( img.complete || img.complete ===undefined) {        

img.src ="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";        

img.src = src;    

}

return img;

}

上一篇下一篇

猜你喜欢

热点阅读