// text,需要生成的文字 // font,字體樣式 drawLogo: function(text, font) { // 創建畫布 let canvas = document.createElement('canvas'); // 繪制文字環境 let context = canvas.getContext('2d'); // 設置字體 context.font = font; // 獲取字體寬度 let width = context.measureText(text).width; // 如果寬度不夠 240 if (width < 240) { width = 240; } else { width = width + 30; } // 畫布寬度 canvas.width = width; // 畫布高度 canvas.height = width; // 填充白色 context.fillStyle = '#ffffff'; // 繪制文字之前填充白色 context.fillRect(0, 0, canvas.width, canvas.height); // 設置字體 context.font = font; // 設置水平對齊方式 context.textAlign = 'center'; // 設置垂直對齊方式 context.textBaseline = 'middle'; // 設置字體顏色 context.fillStyle = '#000000'; // 繪制文字(參數:要寫的字,x坐標,y坐標) context.fillText(text, canvas.width / 2, canvas.height / 2); // 生成圖片信息 let dataUrl = canvas.toDataURL('image/png'); return dataUrl; },