一:canvas转base64 背景色问题
/** * Canvas 转 base64 * @param canvas:canvas元素 * @param backgroundColor:背景色 **/ canvasToImage:function (canvas,backgroundColor) { var w = canvas.width; var h = canvas.height; var context = canvas.getContext("2d"); var data; if(backgroundColor) { //get the current ImageData for the canvas. data = context.getImageData(0, 0, w, h); //store the current globalCompositeOperation var compositeOperation = context.globalCompositeOperation; //set to draw behind current content context.globalCompositeOperation = "destination-over"; //set background color context.fillStyle = backgroundColor; //draw background / rect on entire canvas context.fillRect(0,0,w,h); } //get the image data from the canvas var imageData = canvas.toDataURL("image/png"); if(backgroundColor){ //clear the canvas context.clearRect (0,0,w,h); //restore it with original / cached ImageData context.putImageData(data, 0,0); //reset the globalCompositeOperation to what it was context.globalCompositeOperation = compositeOperation; } //return the Base64 encoded data url string return imageData; },
//Echarts 转 base64
var baseCanvas = $("#container").find("canvas").first()[0];//获取原生的canvas
var base64Img = TMS.canvasToImage(baseCanvas,‘#fff‘); //获得base64
/**
* Canvas 转 base64
* @param canvas:canvas元素
* @param backgroundColor:背景色
**/
canvasToImage:function (canvas,backgroundColor) {
var w = canvas.width;
var h = canvas.height;
var context = canvas.getContext("2d");
var data;
if(backgroundColor) {
//get the current ImageData for the canvas.
data = context.getImageData(0, 0, w, h);
//store the current globalCompositeOperation
var compositeOperation = context.globalCompositeOperation;
//set to draw behind current content
context.globalCompositeOperation = "destination-over";
//set background color
context.fillStyle = backgroundColor;
//draw background / rect on entire canvas
context.fillRect(0,0,w,h);
}
//get the image data from the canvas
var imageData = canvas.toDataURL("image/png");
if(backgroundColor){
//clear the canvas
context.clearRect (0,0,w,h);
//restore it with original / cached ImageData
context.putImageData(data, 0,0);
//reset the globalCompositeOperation to what it was
context.globalCompositeOperation = compositeOperation;
}
//return the Base64 encoded data url string
return imageData;
},
原文:https://www.cnblogs.com/MJ-MY/p/12161702.html