js將字符串轉圖片


/**
 * @param string val 要轉成圖片的字符串
 */
function textToImg(val) {
    var len = 12;/*文字長度*/
    var i = 0;
    var fontSize = 12;/*文字大小*/
    var fontWeight = 'normal';/*normal正常;bold粗*/
    var txt = val;
    var canvas = document.createElement("canvas");
    if (txt == '') {
        alert('請輸入文字!');
        
    }
    if (len > txt.length) {
        len = txt.length;
    }
    canvas.width = fontSize * len;
    canvas.height = fontSize * (3 / 2)
            * (Math.ceil(txt.length / len) + txt.split('\n').length - 1);
    var context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillStyle = '#333';/*顏色*/
    context.font = fontWeight + ' ' + fontSize + 'px 微軟雅黑';
    context.textBaseline = 'top';
    canvas.style.display = 'none';
    //console.log(txt.length);
    function fillTxt(text) {
        while (text.length > len) {
            var txtLine = text.substring(0, len);
            text = text.substring(len);
            context.fillText(txtLine, 0, fontSize * (3 / 2) * i++,
                    canvas.width);
        }
        context.fillText(text, 0, fontSize * (3 / 2) * i, canvas.width);
    }
    var txtArray = txt.split('\n');
    for (var j = 0; j < txtArray.length; j++) {
        fillTxt(txtArray[j]);
        context.fillText('\n', 0, fontSize * (3 / 2) * i++, canvas.width);
    }
    var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
    //var img = $("img");
    //img.src = canvas.toDataURL("image/png");
    return canvas.toDataURL("image/png");
}

太久遠了,已經忘記是從哪里轉載的了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM