如何使用 javascript 将 bootstrap 图标添加到 canvas?如果有办法

How do you add a bootstrap icon to an canvas, using javascript? If there is a way

这是我到目前为止尝试过的方法。

     ctx.setAttribute("class", "glyphicon glyphicon-time");

还有;

    var icon = document.createElement("span");

    icon.className ="glyphicon glyphicon-time";
    this.appendChild(icon);

您可以使用 html2canvas.js

以下代码可能对您有所帮助:

HTML

<span class="glyphicon glyphicon-align-left"></span>

<canvas id="canvas" width="300" height="300"></canvas>

JS

html2canvas(document.querySelector('.glyphicon'), {
    onrendered: function(canvas) {
        var myCanvas = document.querySelector('#canvas');
        var ctx = myCanvas.getContext('2d');
        var img = new Image;

        img.onload = function(){
            ctx.drawImage(img,0,0);
        };

        img.src = canvas.toDataURL();

        document.querySelector('.glyphicon').style.display = 'none';
    }
});

这里是fiddle:http://jsfiddle.net/k7moorthi/qpyj02k8/

在这里,我使用 html2canvas.js 将 html 代码呈现为 canvas,它将动态创建 return 内存中的 canvas 元素(如果需要,您可以将其附加到某些元素)。我不想使用动态创建的 canvas 因为当我想更新 canvas 内容时它会导致一些问题。所以我只获取 canvas 的数据 url,将其转换为图像对象并将其绘制到我已经存在的 canvas 元素中。

编辑:

正如@Patrick Evans提到的,你可以直接使用fillText()方法将gylphicon渲染成canvas。

HTML

<canvas id="canvas" width="300" height="300"></canvas>

CSS

@font-face {
    font-family: 'glyphicon';
    src: url('glyphicons-halflings-regular.eot'); /* IE9 Compat Modes */
    src: url('glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
        url('glyphicons-halflings-regular.woff2') format('woff2'), /* Super Modern Browsers */
        url('glyphicons-halflings-regular.woff') format('woff'), /* Pretty Modern Browsers */
        url('glyphicons-halflings-regular.ttf')  format('truetype'), /* Safari, Android, iOS */
        url('glyphicons-halflings-regular.svg#svgFontName') format('svg'); /* Legacy iOS */
}

JS

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

ctx.font = '20px glyphicon';

ctx.fillText(String.fromCharCode(0x2a), 10, 50);

这是更新后的 fiddle:http://jsfiddle.net/k7moorthi/qpyj02k8/3/

要获取图标的字符代码,请使用 gylphicon cheat sheet。单击作弊 sheet 上每个图标下方的复制下拉菜单,然后单击 Unicode HTML 实体 。现在 unicode 值将被复制到您的剪贴板。它看起来像这样 &#x2a;。将 &# 替换为 0 并删除 ; 以获取字符代码。

无法评论缺乏声誉,但可以回答您关于为什么不能绘制十六进制代码中包含 e 的任何内容的问题。这是因为你需要使用字体

ctx.font = '12px glyphicons halflings';

而不只是字形。