JSFiddle - React, Tailwind, and code Playground
by SundayKDR
HTML
<div class="port">
<canvas id="canvas"></canvas>
<canvas id="canvas2"></canvas>
</div>
CSS
port {
position: relative;
}
port > canvas{
position: absolute;
background-color: transparent;
}
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 800;
canvas.height = 800;
var drawing = true;
var draw = false;
var balls = [];
var lineCords = [];
const lineCord = function(x, y) {
this.x = x;
this.y = y;
};
const rectParam = {
w: 20,
h: 20,
};
var mouse = {
x: 0,
y: 0,
};
const Rect = function (color, x, y, width, height) {
this.color = color;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.draw = function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.clear = function() {
ctx.clearRect(this.x, this.y, this.width, this.height);
}
this.update = function() {
if(lineCords.indexOf({x:this.x, y:this.y}) != -1){
popped = lineCords.pop();
this.x = popped.x;
this.y = popped.y;
return;
}
if (this.x < 0)
this.vX = -this.vX;
if (this.x + this.width > canvas.width)
this.vX = -this.vX;
this.x += this.vX;
}
}
function play() {
balls.forEach(function(item) {
item.clear();
item.update();
item.draw();
});
}
function mousePositionSet(e) {
mouse.x = e.pageX - canvas.offsetLeft;
mouse.y = e.pageY - canvas.offsetTop;
}
var borderLeft = 20;
var borderTop = 40;
var linesCounter = 0;
function displayCords(){
lineCords.forEach(function(item){
testLine = " X: " + item.x + " Y: " + item.y;
linesCounter++;
borderTop += 20;
if(linesCounter*20 > canvas.height){
borderLeft += ctx.measureText(testLine).width;
borderLeft += 20;
borderTop = 20;
linesCounter = 0;
}
ctx.fillText(testLine, borderLeft, borderTop);
})
ctx.moveTo(borderLeft, borderTop + 5);
ctx.lineTo(borderLeft +80, borderTop +5);
ctx.stroke();
}
canvas.addEventListener("mousedown", function(e) {
mousePositionSet(e);
if(e.shiftKey){
//displayCords();
let newBall = new Rect('red',...