文本生成圖片,用于動態(tài)文字作為模型貼圖

可復制:

// 創(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資源}

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容