JSFiddle - React, Tailwind, and code Playground

by michelejs

HTML

<canvas id="canvas" width="500" height="300">
    
</canvas>

CSS

canvas {
    border: 3px solid #000;
}

JavaScript

var canvasWidth;
var canvasHeight;
var interval = 10;
var pos = 0;
var increment = 2;

function init() {
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext('2d');
    canvasWidth = canvas.width;
    canvasHeight = canvas.height;

    setInterval(function () {
        redraw();
    }, interval);
}

init();

function redraw() {
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
    ctx.save();

    ctx.translate(canvasWidth / 2 - 50, 0 + pos);
    ctx.fillText("Hello world", 0, 0);

    ctx.restore();

    pos = pos + increment;
    if(pos > canvasHeight)
        increment = -10;
    else if(pos <= 0)
        increment = 2;
}