JSFiddle - React, Tailwind, and code Playground
HTML
<section>
<div id="kanvas" style="position:relative; width:400px; height:300px">
<canvas id="layer1" style="z-index: 1;
position:absolute;
left:0px;
top:0px;
" height="300px" width="400">This text is displayed if your browser does not support HTML5 Canvas.</canvas>
<canvas width="100" height="100" style="z-index: 2;pointer-events: none;position:absolute;left:50%;top:50%;" id="layer2">This text is displayed if your browser does not support HTML5 Canvas.</canvas>
</div>
</section>
JavaScript
var layer1;
var layer2;
var ctx1;
var ctx2;
var x = 400;
var y = 300;
var dx = 2;
var dy = 4;
var WIDTH = 400;
var HEIGHT = 300;
var interval = null;
var radius = 50;
function init() {
//city.src ="city.png";
layer1 = document.getElementById("layer1");
ctx1 = layer1.getContext("2d");
layer2 = document.getElementById("layer2");
ctx2 = layer2.getContext("2d");
drawAll();
//interval = setInterval(drawAll, 0.5);
$("#layer1").click(function(e){
if(distance(x,y,e.offsetX, e.offsetY) < 2*radius) {
if(interval) {
clearInterval(interval);
interval = null;
}
else {
interval = setInterval(drawAll, 0.5);
}
}
});
}
function drawAll() {
drawBall();
drawRectangle();
}
function drawBall() {
if (x + dx > WIDTH || x + dx < 0) dx = -dx;
if (y + dy > HEIGHT || y + dy < 0) dy = -dy;
x += dx;
y += dy;
ctx1.clearRect(0, 0, WIDTH, HEIGHT);
ctx1.fillStyle = "#444444";
ctx1.beginPath();
ctx1.arc(x, y, radius, 0, Math.PI * 2, true);
//ctx1.arc(x, y, 100, 0, Math.PI*2, true);
ctx1.closePath();
ctx1.fill();
}
function distance(x1,y1,x2,y2) {
return Math.sqrt(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2));
}
function drawRectangle() {
ctx2.clearRect(0, 0, WIDTH, HEIGHT);
ctx2.fillStyle = "blue";
ctx2.save();
ctx2.translate(20, 20);
//ctx2.rotate(x/20);
ctx2.fillRect(-15, -15, 100, 100);
ctx2.restore();
}
init();