HTML5 karaoke

    I decided to try to make web-karaoke, but so that the text is beautifully displayed - not literally, but smoothly. The solution turned out to be simpler than I thought.

    The literal version is quite simple - just do the CSS, see the example on JSFiddle .

    A more beautiful option is to use canvas and color the text using the gradient style:
    var gradient = ctx.createLinearGradient(0, 0, 30, 0);
    gradient.addColorStop(0.00, 'yellow');
    gradient.addColorStop(0.01, 'black');
    gradient.addColorStop(1.00, 'black');
    ctx.fillStyle = gradient;

    The gradient itself (in the form of a transition of one color to another - see the figure on the left below) is not needed to display karaoke, therefore an additional point is used - 0.01, so that the main part of the “gradient” (0.01-1.00) remains black and the small part ( 0.00-1.00) - yellow (see the figure to the right below):

    (an alternative is to set a small value for the third parameter - x1 (end of the gradient) - in createLinearGradient ).

    However, if you simply draw the text:
    ctx.fillText(text, 0, 0);

    then it will be displayed in only one color - black:

    The fact is that the gradient is applied relative to the origin of the coordinate system. In the figure above, point 0 on the x axis is displayed as a black vertical line (shifted along the x axis to the middle of the canvas using the translate method ). To apply the gradient, just draw the text with an offset. The part that is to the left of the x- axis origin will be colored yellow, and the part to the right will be black:
    ctx.fillText(text, -190, 0);

    To display karaoke, now you just need to shift the origin of the coordinate system along the x axis (for example, in a cycle, by one pixel) - the text will gradually turn yellow. You can try coloring the text with a shift in the position of the text (without shifting the origin) at JSFiddle (the grid and design are taken from this article). In the final project, you can see what happened here (you need a VK account).

    Also popular now: