0

I'm trying to create a text fadein function for canvas, but the iterations in the function below cause blurred (and clipped) text.

Troubleshooting Notes

I've tried all the following, but get the same result:

  • using setInterval and setTimeout in lieu of requestAnimationFrame:

  • various "dpr fixes".

  • parseInt fix for textPosX and textPosY parameters.

  • hardcoding rgb values.

In all cases above, the text is blurry and the bottom of the chars is slightly clipped.

However, when I set fadeInAlpha to 100 (to force a single iteration), the text displays clearly, so I'm pretty sure the problem is the iteration - somehow, I can't draw text in precisely the same location multiple times.

    function drawBlockLinesItem ( textLine, textPosX, textPosY ) {
        let fadeInAlpha = 0;
        window.requestAnimationFrame ( () => fadeIn ( fadeInAlpha ) );
        
        function fadeIn ( fadeInAlpha ) {
        fadeInAlpha ++; 
        ctxLayerText.strokeStyle = "rgb(" +
                textStrokeStyleRGB.r + "," + textStrokeStyleRGB.g + "," + textStrokeStyleRGB.b + "," + fadeInAlpha / 100 + ")"
        ctxLayerText.fillStyle = "rgb(" +
                textFillStyleRGB.r + "," + textFillStyleRGB.g + "," + textFillStyleRGB.b + "," + fadeInAlpha / 100 + ")"

            if ( canvasLayerText.width < canvasMinWidthOverride ) {
                ctxLayerText.fillText ( textLine, textPosX, textPosY );
            } else {
                ctxLayerText.strokeText ( textLine, textPosX, textPosY );
            }

            console.log ( "item - " + textValue.substr ( 0, 20 ) + " - draw - " + fadeInAlpha );

            if ( fadeInAlpha < 100 ) {
                window.requestAnimationFrame ( () => fadeIn ( fadeInAlpha ) );
            }
        }
    }

IMTanuki
  • 117
  • 1
  • 9

1 Answers1

0

Turns out - double quotes in the rgb parameters don't work - or at least, they seem to throw off the text rendering:

causes blurry text:

ctxLayerText.fillStyle = "rgb(" +
                textFillStyleRGB.r + "," + textFillStyleRGB.g + "," + textFillStyleRGB.b + "," + fadeInAlpha / 100 + ")"

text displays fine:

ctxLayerText.fillStyle = ‘rgb(‘ +
                textFillStyleRGB.r + ‘,’ + textFillStyleRGB.g + ‘,’ + textFillStyleRGB.b + ‘,’ + fadeInAlpha / 100 + ‘)’

Comment There are a number of other "dpr" adjustment routines that have been posted - IMO, all they do is adjust the canvas height and width, but they don't alter the text rendering:

function initHDPCanvas02 ( canvas, w, h, ratio ) {
    let ctx = canvas.getContext ( '2d' );
    if ( ! ratio ) {
        ratio = calcDevicePixelRatio ( ctx );
    }
    canvas.width = w * ratio;
    canvas.height = h * ratio;
    canvas.style.width = w + "px";
    canvas.style.height = h + "px";
    ctx.setTransform ( ratio, 0, 0, ratio, 0, 0 );
    return ctx;
}
IMTanuki
  • 117
  • 1
  • 9