Hej,
Mam problem nie wyświetlają mi się kropki po najechaniu myszką sam canvas wyłapuje cordsUpdate ale nie ma żadnej reakcji na ekran nie wiem czym jest to spowodowane
import React, { useEffect, useRef, useState } from "react";
function Canvas() {
// <!-- inspiration was taken from 'juliangarnier'" -->
const [drawing, SetDrawing] = useState(false);
//creating refernes to jsx object
const canvasRef = useRef(null);
useEffect(() => {
if (!canvasRef.current) {
return;
}
const canvas = canvasRef.current;
const context = canvas.getContext("2d");
//function setting Window Size
function windowSize() {
canvas.width = window.innerWidth * 2;
canvas.height = window.innerHeight * 2;
canvas.style.height = window.innerHeight + "px";
canvas.style.width = window.innerWidth + "px";
context.scale(2, 2);
}
//Updating the mouse cords
const CordsUpdate = {
x: undefined,
y: undefined,
};
// Array of all parts
let PartArray = [];
//colors of cirlce
let colorsofCircles = ["#780000", "#c1121f", "#fdf0d5", "#003049", "#669bbc"];
let numberOfCircles = 5;
//constructor adds new Particles
function Part() {
//setting variables to mousemove
this.x = CordsUpdate.x;
this.y = CordsUpdate.y;
//Size of circle
this.radius = Math.random() * 15 + 1;
//direction of circles
this.motionX = Math.random() * 4 - 2;
this.motiony = Math.random() * 4 - 2;
this.color = colorsofCircles[Math.round(Math.random() * this.colorsofCircles.length - 1)];
}
//animation moving and shrink circles
Part.prototype.motion = function () {
this.x += this.motionX;
this.y += this.motionY;
if (this.radius > 0.1) this.radius -= 0.1;
};
//Creating a cricle
Part.prototype.draw = function () {
context.fillStyle = this.color;
context.beginPath();
context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
context.fill();
};
//trigger motion and draw
function makeThemBe() {
for (let i = 0; i < PartArray.length; i++) {
PartArray[i].motion();
PartArray[i].draw();
if (PartArray[i].radius <= 0.3) {
PartArray.splice(i, 1);
i--;
}
}
}
//display
function animate() {
context.clearRect(0, 0, canvas.width, canvas.height);
makeThemBe();
requestAnimationFrame(animate);
}
//mouse follow spray the circles
canvas.addEventListener("mousedown", function () {
SetDrawing((prev) => (prev = true));
});
canvas.addEventListener("mousemove", function (event) {
if (drawing === true) {
for (let i = 0; i < numberOfCircles.length; i++) {
PartArray.push(new Part());
}
CordsUpdate.x = event.offsetX;
CordsUpdate.y = event.offsetY;
}
});
canvas.addEventListener("mousedown", function () {
if (drawing === true) {
SetDrawing((prev) => (prev = false));
}
});
animate();
windowSize();
//clean up component
return () => {
window.removeEventListener("mousedown", function () {});
canvas.removeEventListener("mousemove", function () {});
canvas.removeEventListener("mousedown", function () {});
};
}, [drawing]);
return <canvas ref={canvasRef}></canvas>;
}
export default Canvas;