function handleClick() { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.fillStyle = "#f03"; var recW = 150; function animate2() { ctx.clearRect(50, 50, canvas.width, recW - 1); ctx.save(); ctx.beginPath(); ctx.rect(50, 50, recW, recW); ctx.clip(); ctx.beginPath(); ctx.arc(100, 100, 90, 0, Math.PI * 2, true); ctx.fill(); ctx.restore(); ctx.beginPath(); ctx.rect(50 - 1, 50 - 1, recW + 2, recW + 2); ctx.lineWidth = 10; ctx.stroke(); console.log(recW); recW++; if (recW < 300) { window.requestAnimationFrame(animate2); } } var run = window.requestAnimationFrame(animate2); } const button = document.getElementById('button'); button.addEventListener('click', handleClick);
<button id="button">START ANIMATION</button> <canvas id="canvas" width="1000" height="1000"></canvas>