

可復制:
// 創(chuàng)建文本圖片// 支持 文字設置大小 字體 顏色 是否3D顯示// 支持 圖片透明度 文字所處圖片位置 最小圖片設置等function createTextCanvas(? ? text, ? ? fontOptions = {font: "20px sans-serif", color: "red", backgroud: "rgba(255, 255, 255, 0.1)"}, ? ? minImgWidht = null, ? ? paddingOptions = {top: 100, right: 0, bottom: 0, left: 20},? ? is3D = true) {? ? ? ? // 創(chuàng)建畫布? ? ? ? let canvas = document.createElement('canvas');? ? ? ? // 繪制文字環(huán)境? ? ? ? let context = canvas.getContext('2d');? ? ? ? // 設置字體? ? ? ? context.font = fontOptions.font;? ? ? ? ? ? ? ? // 獲取字體寬度? ? ? ? let width = context.measureText(text).width;? ? ? ? if(typeof(minImgWidht) == 'number' && width < minImgWidht) {? ? ? ? ? ? width = minImgWidht;? ? ? ? }? ? ? ? width += paddingOptions.left + paddingOptions.right;? ? ? ? // 獲取字體高度? ? ? ? let height = context.measureText(text).fontBoundingBoxAscent ? ? ? ? ? ? + context.measureText(text).fontBoundingBoxDescent? ? ? ? ? ? + paddingOptions.top + paddingOptions.bottom;? ? ? ? // 畫布寬度? ? ? ? canvas.width = width;? ? ? ? // 畫布高度? ? ? ? canvas.height = height;? ? ? ? // 填充背景? ? ? ? context.fillStyle = fontOptions.backgroud;? ? ? ? // 繪制背景大小? ? ? ? context.fillRect(0, 0, canvas.width, canvas.height);? ? ? ? // 設置字體? ? ? ? context.font = fontOptions.font;? ? ? ? // 設置字體顏色? ? ? ? context.fillStyle = fontOptions.color;? ? ? ? if(is3D) {? ? ? ? ? ? var n;? ? ? ? ? ? //繪制底層? ? ? ? ? ? for (n=0; n<2; n++)? ? ? ? ? ? {? ? ? ? ? ? ? ? context.fillText(text,Math.abs(paddingOptions.left)-n,Math.abs(parseInt(fontOptions.font) + paddingOptions.top)-n);? ? ? ? ? ? }? ? ? ? ? ? context.shadowColor="black";? ? ? ? ? ? context.shadowBlur=1;? ? ? ? ? ? context.shadowOffsetX=1;? ? ? ? ? ? context.shadowOffsetY=0;? ? ? ? }? ? ? ? ? ? ? ? // 沒有填寫坐標則默認居中輸出? ? ? ? if(paddingOptions.top == 0 ? ? ? ? ? ? && paddingOptions.right == 0 ? ? ? ? ? ? && ?paddingOptions.bottom == 0 ? ? ? ? ? ? && paddingOptions.left == 0) {? ? ? ? ? ? // 設置水平對齊方式? ? ? ? ? ? context.textAlign = 'center';? ? ? ? ? ? // 設置垂直對齊方式? ? ? ? ? ? context.textBaseline = 'middle';? ? ? ? ? ? // 填充文字(參數(shù):要寫的字,x坐標,y坐標)? ? ? ? ? ? context.fillText(text, canvas.width/2, canvas.height/2);? ? ? ? }? ? ? ? else {? ? ? ? ? ? // 填充文字(參數(shù):要寫的字,x坐標,y坐標)? ? ? ? ? ? context.fillText(text, Math.abs(paddingOptions.left), ? ? ? ? ? ? ? ? Math.abs(parseInt(fontOptions.font) + paddingOptions.top));? ? ? ? }? ? ? ? // 生成圖片信息? ? ? ? // return canvas.toDataURL('image/png'); // 圖資源? ? ? ? return canvas; // canvas資源}