Very new to Canvas. I've created an object "Triangle" and have figured out how to instantiate it and have it move along the x and y axis. I've even figured out how to add interactivity (on mouse hover, object changes direction). The thing that's getting me is rotate. I've tried a million ways but just do not understand how to do it. I've managed to get the entire group of objects to rotate seemingly at point 0, 0. I'd like each object to rotate on its own axis. Any help would be appreciated!
var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext('2d');
img = new Image();
var randomNumber = getRandomInt(2);
var imgArray = ["https://i.imgur.com/efLA0Or.jpg?1", "https://i.imgur.com/efLA0Or.jpg?1"];
img.src = imgArray[randomNumber];
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
var mouse = {
x: undefined,
y: undefined
}
window.addEventListener('mousemove',
function(event) {
mouse.x = event.x;
mouse.y = event.y;
})
function Circle(x, y, dx, dy, radius, rotation) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.draw = function() {
c.drawImage(img, this.x, this.y, 100, 100);
}
this.update = function() {
c.rotate(rotation);
if (this.x + this.radius > innerWidth || this.x - this.radius < 0) {
this.dx = -this.dx;
}
if (this.y + this.radius > innerHeight || this.y - this.radius < 0) {
this.dy = -this.dy;
}
this.y += this.dy;
//interactivity
if (mouse.x - this.x < 100 && mouse.x - this.x > -100
&& mouse.y - this.y < 100 && mouse.y - this.y > -100
) {
this.dx = -dx * 2;
this.dy = -dy * 2;
}
this.draw();
}
}
var circleArray = [];
for (var i = 0; i < 100; i++) {
var x = Math.random() * (innerWidth - radius * 2) + radius;
var y = Math.random() * (innerHeight - radius * 2) + radius;
var dx = (Math.random() - 0.5) * 1;
var dy = (Math.random() - 0.5) * 1;
var radius=30;
var rotation = Math.PI/180;
circleArray.push(new Circle(x, y, dx, dy, radius, rotation));
}
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, innerWidth, innerHeight);
for (var i = 0; i < circleArray.length; i++){
circleArray[i].update();
}
}
animate();
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="canvas.css">
<script src="canvas.js"></script>
</head>
<body>
<div id="container">
<canvas></canvas>
<script src="canvas.js"></script>
</div>
</body>
</html>