简体   繁体   中英

How to efficiently style individual characters in an element?

I've been working on a 2D graphics framework running inside only HTML text (ie the individual characters act as pixels). Naturally, I need the code to be as efficient as possible as I am aiming to be able to run this as close to 60 fps as possible.

Each row of characters is it's own HTML paragraph element. I noticed when I added functionality for colouring each individual character the code suffered a massive dip in performance (around 60 fps down to about 5 or 6).

My method to colour the individual % characters

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

Where colour is the hex value of the desired colour.

I've looked around for some time now but haven't been able to find any solution that is compatible with the dynamic nature of the styling I'm trying to do. Does anybody know of a more efficient way of styling individual characters on the fly? Also, an insight into why the above method is so inefficient would also be helpful.

Thanks (For a look at the code in context take a look at https://a8afefdfe4646d1a727ae236e436a4e29773afd3.googledrive.com/host/0BwftsCVGDOiwQ0I4WUxRTEFuWkU/TextCanvas.js , the drawChar and render functions are where the styling code is)

First off, the font tag is deprecated. use span .

Also, this answer assumes you have to do it this way instead of the much better canvas element to draw.

What you should do when creating the elements is:

//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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM