JSFiddle - React, Tailwind, and code Playground

by vietean

HTML

<canvas id="canvas" width="840px" height="320px" style="position:absolute;">
</canvas>

JavaScript

/*@const*/
var SCALE_X = 1;
var SCALE_Y = 1;
var POINTX = 100;
var POINTY = 100;
var POINTX2 = 700;
var POINTY2 = 100;
var NKEY = 10;
var WIDTH = 40;
var HEIGHT = 10;
var centerX = WIDTH / 2;
var centerY = HEIGHT / 2;
var detaX = (POINTX2 - POINTX) / NKEY;
var detaY = (POINTY2 - POINTY) / NKEY;
var angle = 0;
var iKey = 0;
var scale = 1;

function draw1() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    ctx.strokeStyle = "rgba(255,0,0,0.5)";
    //Ve mot cai duong nam ngang ma cac diem center nam tren do
    ctx.beginPath();
    ctx.moveTo(POINTX + centerX, POINTY + centerY);
    ctx.lineTo(POINTX2 + centerY, POINTY2 + centerY);
    ctx.fillStyle = "rgba(0, 0,128, 0.5)";
    ctx.stroke();
    ctx.save();
    ctx.translate(POINTX + detaX * iKey + centerX, POINTY + detaY * iKey + centerY);
    ctx.rotate(angle * 2 * Math.PI / 360);
    ctx.save();
    ctx.scale(scale, scale);
    //Ve cai hinh chu nhat sau khi da scale, rotate tai center
    ctx.fillRect(-centerX, -centerY, WIDTH, HEIGHT);
    ctx.restore();
    ctx.fillStyle = "#FF0000";
    ctx.beginPath();
    ctx.arc(0, 0, 2, 0, Math.PI * 2, true);
    ctx.fill();
    ctx.restore();
    iKey++;
    //Tang goc xoay
    angle += 1.5;
    //Tang scale
    scale += 0.1;
    if (iKey < NKEY) {
        setTimeout(draw1, 1000)
    }
}
draw1();