Created
March 24, 2022 01:38
-
-
Save tknr/0f5bf7b914c171d43042930f8f5f0464 to your computer and use it in GitHub Desktop.
文字列から画像生成
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String.prototype.toZenkaku = function () { | |
return String(this).replace(/[!-~]/g, function (all) { | |
return String.fromCharCode(all.charCodeAt(0) + 0xFEE0); | |
}); | |
} | |
String.prototype.chunk = function (length) { | |
return this.match(new RegExp('.{1,' + length + '}', 'g')); | |
} | |
/** | |
* | |
* @param {element} element | |
* @param {string} word 画像内に表示する文言 | |
* @param {number} width px | |
* @param {number} height px | |
* @param {number} fontSize px フォントサイズ default : 24 | |
* @param {number} lineWidth px 枠線の太さ default : 3 | |
* @param {string} fontColor default : 'black' | |
* @param {string} lineColor default : 'black' | |
* @param {string} bgColor default : 'white' | |
* @param {string} fontStyle default : 'bold ' | |
* @param {string} fontFamily default : 'Arial, meiryo, sans-serif' | |
*/ | |
function drawThumbnailFromText( | |
element, word, width, height, | |
fontSize = 24, lineWidth = 3, | |
fontColor = 'black', lineColor = 'black', bgColor = 'white', | |
fontStyle = 'bold ', | |
fontFamily = 'Arial, meiryo, sans-serif' | |
) { | |
console.log(arguments); | |
var canvas = $('<canvas id="canvas"/>').attr({ 'width': width, 'height': height }); | |
element.empty(); | |
element.append(canvas); | |
const ctx = canvas.get(0).getContext("2d"); | |
// 塗りつぶし | |
ctx.beginPath(); | |
ctx.fillStyle = bgColor; | |
ctx.fillRect(0, 0, width, height); | |
if (word) { | |
// テキスト設定 | |
ctx.font = fontStyle + fontSize + 'px ' + fontFamily; | |
ctx.textBaseline = 'center'; | |
// キャンバスサイズとフォントサイズから1行あたりの最大文字数を決める | |
var char_max_count = Math.floor(width / fontSize); | |
console.log([char_max_count]); | |
// 文字数のカウントと改行のため、半角文字を全角化 | |
var zenkakuWord = word.toZenkaku(); | |
console.log([zenkakuWord]); | |
cdn4 = zenkakuWord.chunk(char_max_count); | |
console.log(cdn4); | |
// 文字色設定 | |
ctx.fillStyle = fontColor; | |
// カウントした文字数ずつ描写 | |
for (let i = 0; i < cdn4.length; i++) { | |
let txt = cdn4[i]; | |
let _x = parseInt(lineWidth); | |
let _y = parseInt(i * fontSize) + parseInt(fontSize) + parseInt(lineWidth); | |
console.log(i, txt, _x, _y); | |
ctx.fillText(txt, _x, _y); | |
} | |
} | |
// 枠線設定 | |
ctx.lineWidth = lineWidth; | |
ctx.strokeStyle = lineColor; | |
ctx.fillStyle = bgColor; | |
// 外枠を書く | |
ctx.moveTo(0, 0); | |
ctx.lineTo(width, 0); | |
ctx.lineTo(width, height); | |
ctx.lineTo(0, height); | |
ctx.lineTo(0, 0); | |
ctx.closePath(); | |
ctx.stroke(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment