JSFiddle - React, Tailwind, and code Playground

by Matthew Ekenstedt

HTML

<button onclick="startScrolling()">Start Scrolling!</button>
<canvas id="canvas1" width="500px" height="100px" />

JavaScript

function startScrolling()
{
    var c = document.getElementById("canvas1");
    var scroller = new Scroller(c, "Welcome to my homepage! Sign my guestbook!");
    scroller.doAnimation();
}

function Scroller(canvas, scrollingText)
{
    this.canvas = canvas;
    this.text = scrollingText;
    this.textWidth = 0;
    this.yloc = 10;
    this.xloc = this.canvas.width;
    this.font = "12px Arial";
    var self = this;
    this.animId;
    this.doAnimation = function()
    {
        this.animId = requestAnimationFrame(function() { self.doAnimation(); });
        if(this.textWidth == 0)
        {
            var context = this.canvas.getContext("2d");
            context.font = this.font;
            this.textWidth = context.measureText(this.text).width;
        }
        if(this.textWidth + this.xloc < 0)
        {
            this.xloc = this.canvas.width;
        }
        else
        {
            this.xloc--;
        }
        this.drawText();
    }
    this.drawText = function()
    {
        var context = this.canvas.getContext("2d");
        context.clearRect(0, 0, this.canvas.width, this.canvas.height);
        context.font = this.font;
        context.fillText(this.text, this.xloc, this.yloc);
    };
}