Effectively colorize each character in HTML

I am trying to visualize the results of some computational analysis on most of the text. Analysis gives me a rating of [0-100) for each character. I have defined some classes:

.c0 { background-color:rgb(6,50,99); } .c1 { background-color:rgb(7,52,102); } .c2 { background-color:rgb(8,54,105); } .c3 { background-color:rgb(10,58,111); } 

and the main part of my document is as follows:

<span class='c76'>i</span><span class='c75'>c</span><span class='c76'>k</span><span class='c73'>l</span><span class='c70'>y</span><span class='c72'>,</span><span class='c76'> </span><span class='c76'>a</span><span class='c78'>n</span><span class='c78'>d</span><span class='c76'> </span><span class='c76'>b</span><span class='c76'>e</span><span class='c76'>

This works well visually (see the blurry screenshot for an example):

enter image description here

but very slow to browse. For large documents, this drags the computer to a standstill. Is there a more efficient way to transfer this information to a browser, perhaps one that uses JavaScript?

+5
source share
1 answer

I would definitely consider using HTML 5 canvas . It stands out separately from the DOM, usually with some form of acceleration. When viewing, there should not be a slowdown, although the initial rendering may still take a second.

You can do something like this to draw a character with a background:

 ctx.font = font; ctx.textBaseline = 'top'; ctx.fillStyle = colour; var width = ctx.measureText(txt).width; ctx.fillRect(x-1, y, width+1, parseInt(font, 10)); ctx.fillStyle = '#000'; ctx.fillText(txt, x, y); 

Here's a jsfiddle with an example for a demo: http://jsfiddle.net/q2cwxnbp/3/

The disadvantage of this method is that the text cannot be selected / copied because it is displayed graphically.

+4
source

Source: https://habr.com/ru/post/1274623/


All Articles