Old School: Rolling and Rotating Text in JavaScript

It’s over midnight, but it is summer… I’ve made this kind of effect in Monkey X earlier. Just tried to make it in JavaScript too. Video:

The source code:

<!DOCTYPE html>
<html lang="fi">
<head>
<link rel="StyleSheet" href="tyylit.css" type="text/css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="utf-8"/>
<title>Rolling and rotating text</title>
</head>
<script>
var canvas = undefined;
var ctx = undefined;
var angle = -270;
var start = 0;
var i = 0;

const SCROLLTEXT = "                                      Rolling and rotating text in JavaScript with alpha...... Source code at my web site....                                       ";

window.onload = function() {
    canvas = document.getElementById("canvas");
    canvas.setAttribute("width",document.documentElement.clientWidth);
    canvas.setAttribute("height",document.documentElement.clientHeight);

    ctx = canvas.getContext("2d");
    ctx.font = "48px courier";

    rotate_text();
}


function rotate_text() {


    ctx.clearRect(0,0,document.documentElement.clientWidth,document.documentElement.clientHeight);

    i = 0;
    let alpha = 0;

    for (let angle2 = -270 - angle; angle2 < -270 + 360 - angle; angle2+=10) {

        letter = SCROLLTEXT.substring(start + i, start + i + 1);

        ctx.save();
        ctx.translate(Math.cos((angle2) * (Math.PI / 180)) * 250, Math.sin(( angle2) * (Math.PI / 180)) * 250);
        ctx.translate(canvas.width / 2, canvas.height / 2);
        ctx.rotate((angle2) * (Math.PI / 180));
        ctx.translate(-canvas.width / 2, -canvas.height / 2);
        ctx.fillStyle = "#1122FF";

        alpha = 1 + Math.cos((angle2 + 90) * Math.PI / 180);
        ctx.globalAlpha = alpha;
        

        ctx.fillText(letter, canvas.width / 2  , canvas.height / 2);
        ctx.restore();  
        
        i++;

    }


    if (angle % 10 == 0) {
        start+=1;
        angle=0;
    } 
    angle += 0.5;
    

    if (start == SCROLLTEXT.length - 36) {
        start = 0;
    }
    

    window.requestAnimationFrame(rotate_text);

}


</script>
<body>
<canvas id="canvas"></canvas>
</body>
</html>

The line where CSS style is loaded is not needed.

Feel free to use the code.

%d bloggers like this: