如何有效地设置元素中各个字符的样式

How to efficiently style individual characters in an element?

本文关键字:字符 样式 有效地 设置 元素      更新时间:2023-09-26

我一直在开发一个仅在HTML文本中运行的2D图形框架(即单个字符充当像素)。当然,我需要代码尽可能高效,因为我的目标是能够以尽可能接近60帧/秒的速度运行。

每一行字符都是它自己的HTML段落元素。我注意到,当我添加为每个单独的字符着色的功能时,代码的性能出现了大幅下降(从大约60帧/秒下降到大约5或6帧)。

我的方法来着色个人%字符

    "<FONT color=" + colour + ">%</FONT>"

其中color是所需颜色的十六进制值。

我已经四处寻找了一段时间,但一直未能找到任何与我尝试的造型的动态特性相兼容的解决方案。有人知道一种更有效的动态造型方式吗?此外,深入了解为什么上述方法效率如此之低也会有所帮助。

谢谢(要查看上下文中的代码,请查看https://a8afefdfe4646d1a727ae236e436a4e29773afd3.googledrive.com/host/0BwftsCVGDOiwQ0I4WUxRTEFuWkU/TextCanvas.js,drawChar和render函数是样式代码所在的位置)

首先,不赞成使用font标记。使用CCD_ 1。

此外,这个答案假设您这样做,而不是使用更好的canvas元素来绘制。

创建元素时应该做的是:

//An example of the colors
var colors = [ "#e8e8e8", "#ffffff" ];
//This will hold them all for fast adding to your parent node
var fragment = document.createDocumentFragment();
for ( var i = 0; i < colors.length; i++ )
{
    //Create the element
    var color = document.createElement( "span" );
    //Set its color
    color.style.color = colors[ i ];
    //Add the % symbol (innerText is IE)
    color.textContent = color.innerText = "%";
    //Add to fragment
    fragment.appendChild( color );  
}
//Now add it to the parent node (will add all the children)
parentNode.appendChild( fragment );