首页 > 其他 > 详细

canvas日常操作

时间:2020-01-07 15:48:29      阅读:129      评论:0      收藏:0      [点我收藏+]

一: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 canvascanvas元素
* @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;
},

canvas日常操作

原文:https://www.cnblogs.com/MJ-MY/p/12161702.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!