how do i rotate a rectangle to point towards mouse - javascript

I need help rotating a rectangle to point towards the mouse on the screen every time the mouse moves. ive been trying to do so using the onmousemove event and calculating degrees/angle, then converting to radians, but for some reason when i place the radians variable rad inside rotate();, the rectangle does not rotate at all.
<!DOCTYPE html>
<html>
<head>
<title>Rotate Rectangle Project</title>
<style>
canvas {
background:#f05424; display: block; margin: 0 auto;
}
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width=500 height=500 top=10px></canvas>
<p id='coord'>0</p>
<p id='degree'>0</p>
<p id='radian'>0</p>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext("2d");
var x = 100;
var y = 100;
var w = 100;
var h = 30;
var rX, rY, mX, mY, degrees, rad, coords;
document.onmousemove = function(e){
rX =533;
rY =100;
mX = e.clientX;
mY = e.clientY;
coords = mX + ',' + mY;
degrees = mY - rY + mX - rX;
rad = Math.atan2(mY - rY, mX - rX)* Math.PI/180;
draw();
document.getElementById('coord').innerHTML = coords;
document.getElementById('degree').innerHTML = degrees;
document.getElementById('radian').innerHTML = rad;
};
function rectangle(){
ctx.beginPath();
ctx.translate(x, y);
ctx.rotate(rad);
ctx.translate(-x, -y);
ctx.rect(x, y, w, h);
ctx.fillStyle = '#f8c778';
ctx.fill();
ctx.closePath();
}
function draw(){
ctx.clearRect(x,y,canvas.width,canvas.height);
rectangle();
}
</script>
</body>
</html>

I have edited your code, basically you need to call rectangle on onmousemove and clear the canvas.
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext("2d");
var x = 100;
var y = 100;
var w = 100;
var h = 30;
var mouseX, mouseY, degrees, rad, coords;
document.onmousemove = function(e) {
mouseX = e.clientX;
mouseY = e.clientY;
coords = mouseX + ',' + mouseY;
degrees = mouseY - y + mouseX - x;
rad = Math.atan2(mouseY - y, mouseX - x) * (180 / Math.PI);
rectangle();
};
function rectangle() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.translate(x, y);
ctx.rotate(rad);
ctx.translate(-x, -y);
ctx.rect(x, y, w, h);
ctx.fillStyle = '#f8c778';
ctx.fill();
ctx.closePath();
}
body {
margin: 0px;
padding: 0px;
}
canvas {
background: #f05424;
display: block;
margin: 0 auto;
}
<canvas id="myCanvas" width=500 height=500></canvas>

Related

check if circle is hovered HTML5 Canvas [duplicate]

I'm new to canvas and I'm trying to listen to mouse clicks on the circles that I previously drew on canvas. I'm trying to change the colour of the circles (maybe to green) when I click on them.
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var radius = 15;
for (var i = 0; i < 600; i += 100) {
var x = 100 + i;
var y = 100;
draw_circle(i, x, y, radius);
}
function draw_circle(ID, x, y, radius) {
context.beginPath();
context.arc(x, y, radius, 0, Math.PI * 2, false);
context.fillStyle = 'red';
context.fill();
context.lineWidth = 3;
context.strokeStyle = 'black';
context.stroke();
context.closePath();
}
<!DOCTYPE HTML>
<html>
<head>
<style>
html,
body {
width: 100%;
height: 100%;
margin: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="700" height="700"></canvas>
</body>
</html>
Just add the arc path again and use isPointInPath() with the mouse position. Only one arc can be tested at once, but it's fast to clear and add new paths. Do this in a loop.
Example
var c = document.querySelector("canvas"), ctx = c.getContext("2d");
getArc(50, 50, 40);
ctx.fill();
c.onclick = function(e) {
var rect = this.getBoundingClientRect(), // get abs. position of canvas
x = e.clientX - rect.left, // adjust mouse-position
y = e.clientY - rect.top;
getArc(50, 50, 40); // get path wo/ filling/stroking it
if (ctx.isPointInPath(x, y)) alert("Clicked");
};
function getArc(x, y, r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2);
ctx.closePath();
}
<canvas></canvas>
The other approach is to use math and trigonometry:
// at this point we have the mouse position, so:
var dx = x - arcX,
dy = y - arcY,
dist = Math.abs(Math.sqrt(dx*dx + dy*dy));
if (dist <= radius) { ...clicked... };
Tip: you can skip squaring the dist by using r2 instead.
With SVG, it would be easy - a circle is an element, and can have a click handler, and has fill that you can manipulate to change colour.
With Canvas, you need to:
save the data for each circle you draw (center and radius)
capture click on canvas as cx, cy
check every circle data x, y, r you have, see whether dx * dx + dy * dy < r * r, where dx = cx - x, dy = cy - y. Circles that satisfy this equation were clicked
repaint the circle
With Canvas, you can use function addEventListener. There are quite a few mouse events you can detect: mousedown, mouseup, mousemove, mouseout and mouseover.
Here is a example:
<!DOCTYPE HTML>
<html>
<head>
<style>
html,
body {
width: 100%;
height: 100%;
margin: 0px;
}
</style>
<script>
function initialize() {
var canvas = document.getElementById("myCanvas");
canvas.addEventListener("mousedown", doMouseDown, false);
}
function doMouseDown() {
canvas_X = event.pageX;
canvas_Y = event.pageY;
alert("X = " + canvas_X + "Y = " + canvas_Y);
}
</script>
</head>
<body>
<canvas id="myCanvas" width="700" height="700"></canvas>
</body>
</html>

How to move an object on a canvas continuously in one direction for as long as the mouse button is down?

I have a red circle with a blue circle circling around it. I am trying to move the red circle in the direction of the blue circle when the mouse button is pressed.
But it currently only moves once.
I would like to have it moving continually while I press the mouse button, so that it keeps moving towards the direction of where the blue circle happens to be, keeping the blue circle ahead of it (and not circling) for as long as the mouse button is down.
Here is my code. Click the mouse button to see the reaction of the red circle:
const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let positionX = 100;
let positionY = 100;
let X = 50;
let Y = 50;
let angle = 0;
canvas.addEventListener('mousedown', function(){
X += positionX;
Y += positionY;
})
function circle(){
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(X, Y, 20, 0, Math.PI*2);
ctx.closePath();
ctx.fill();
}
function direction(){
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc(positionX + X, positionY + Y, 10, 0, Math.PI*2);
ctx.closePath();
positionX = 35 * Math.sin(angle);
positionY = 35 * Math.cos(angle);
angle += 0.1;
ctx.fill();
}
function animate(){
ctx.clearRect(0,0, canvas.width, canvas.height);
circle();
direction();
requestAnimationFrame(animate);
}
animate();
#canvas1{
position: absolute;
top:0;
left: 0;
width: 100%;
height: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas1"></canvas>
<script src="script.js"></script>
</body>
</html>
If you want to continually have the red circle move towards the blue one, for as long as the mouse button is down, then you need to maintain the state of the mouse button. You can do that by keeping a global flag updated with a handler for the mousedown and the mouseup event.
Then move the code that updates X and Y into the animation loop: make that update when the flag is true (when the mouse button is down). On the other hand, only update the angle (for the blue circle) when the mouse button is not down:
const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let positionX = 100;
let positionY = 100;
let X = 50;
let Y = 50;
let angle = 0;
let mouseButtonDown = false;
document.addEventListener('mousedown', () => mouseButtonDown = true);
document.addEventListener('mouseup', () => mouseButtonDown = false);
function circle(){
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(X, Y, 20, 0, Math.PI*2);
ctx.closePath();
ctx.fill();
}
function direction(){
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc(positionX + X, positionY + Y, 10, 0, Math.PI*2);
ctx.closePath();
positionX = 35 * Math.sin(angle);
positionY = 35 * Math.cos(angle);
ctx.fill();
}
function animate(){
if (mouseButtonDown) {
X += positionX / 10;
Y += positionY / 10;
} else {
angle += 0.1;
}
ctx.clearRect(0,0, canvas.width, canvas.height);
circle();
direction();
requestAnimationFrame(animate);
}
animate();
#canvas1{
position: absolute;
top:0;
left: 0;
width: 100%;
height: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas1"></canvas>
<script src="script.js"></script>
</body>
</html>

Rotating and moving object (follow into mouse) - Javascript

everybody!
I want to make a small tank that will follow the mouse and turn its cannon towards the mouse.
I made a deal following the mouse, but there is no way I can turn the gun towards the mouse.
My code:
// canvas variable
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// browser window size
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
//set canvas size
canvas.width = windowWidth;
canvas.height = windowHeight;
var mouseX = 0;
var mouseY = 0;
var baseAngle = 1;
class Cannon {
constructor(x,y, angle, size, speed){
this.x = x;
this.y = y;
this.angle = angle;
this.size = size;
this.speed = speed;
}
draw() {
// bullet
ctx.setTransform(1, 0, 0, 1, this.x, this.y - (this.size/2));
ctx.translate(this.x, this.y);
ctx.rotate(baseAngle);
ctx.beginPath();
ctx.rect(this.x, this.y - (this.size/2), this.size*2, this.size);
ctx.fillStyle = 'rgb(192,192,192)';
ctx.fill();
ctx.lineWidth = 3;
ctx.strokeStyle = 'rgba(128,128,128)';
ctx.stroke();
ctx.closePath();
//body
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
ctx.fillStyle = 'rgb(0,96,255)';
ctx.fill();
ctx.lineWidth = 3;
ctx.strokeStyle = 'rgba(128,128,128)';
ctx.stroke();
ctx.closePath();
}
update() {
// mooving
var dx = (mouseX - this.x)*.125;
var dy = (mouseY - this.y)*.125;
var dist = Math.sqrt(dx*dx + dy*dy);
if(dist > this.speed){
dx *= this.speed / dist;
dy *= this.speed / dist;
}
this.x += dx;
this.y += dy;
// rootating
baseAngle = Math.atan2(mouseY - this.y, mouseX - this.x);
}
}
const newCannon = new Cannon(80,60, 1, 20, 7);
onmousemove = function(e){
mouseX = e.clientX;
mouseY = e.clientY;
}
function gameUpdate() {
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
ctx.clearRect(0, 0, canvas.width, canvas.height);
newCannon.draw();
newCannon.update();
requestAnimationFrame(gameUpdate);
}
gameUpdate();
<!DOCTYPE html>
<html>
<head>
<title>CRUSH DEMO</title>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>
The cannon must be rotated in the direction of the mouse (the circle itself must not be rotated).
help me please fix the code!

Ball is bouncing from the centre not the edge

I have coded a ball to bounce around on a canvas, however, the ball only bounces from the centre, not the edge.
I have already tried putting the radius instead of the x and y but that didn't help at all, as of right now I am out of ideas.
I expect the ball to bounce of the edges of itself rather than the centre of it
<!DOCTYPE>
<html>
<head>
<title>Ball Bounce</title>
<style>
canvas {
border-width: 5px;
border-style: ridge;
border-color: #FF0000;
}
</style>
</head>
<body>
<canvas id="testCanvas" width="700" height="400"></canvas>
<script>
var canvas = document.getElementById("testCanvas");
var ctx = canvas.getContext("2d");
var x = 300;
var y = 300;
var radius = 50;
var circleColour = "green";
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var dx = 2;
var dy = -2;
function circle(x, y, r, c) {
ctx.beginPath();
ctx.arc(x, y, r, 0, 2 * Math.PI, false);
ctx.fillStyle = c;
ctx.fill()
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
circle(x, y, radius, circleColour)
if (y<0 || y > canvasHeight){
dy = -dy;
}
if (x>canvasWidth || x<0){
dx = -dx;
}
x = x + dx;
y = y + dy;
}
setInterval(draw, 5.5);
</script>
</body>
</html>
I have already tried putting the radius instead of the x and y but that didn't help at all...
You need to combine the radius with x and y (or the canvas edges) to make sure the ball changes direction at all four borders.
if (y - radius < 0 || y + radius > canvasHeight) {
dy = -dy;
}
if (x + radius > canvasWidth || x - radius < 0) {
dx = -dx;
}

Detect mouse clicks on circles on HTML5 canvas

I'm new to canvas and I'm trying to listen to mouse clicks on the circles that I previously drew on canvas. I'm trying to change the colour of the circles (maybe to green) when I click on them.
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var radius = 15;
for (var i = 0; i < 600; i += 100) {
var x = 100 + i;
var y = 100;
draw_circle(i, x, y, radius);
}
function draw_circle(ID, x, y, radius) {
context.beginPath();
context.arc(x, y, radius, 0, Math.PI * 2, false);
context.fillStyle = 'red';
context.fill();
context.lineWidth = 3;
context.strokeStyle = 'black';
context.stroke();
context.closePath();
}
<!DOCTYPE HTML>
<html>
<head>
<style>
html,
body {
width: 100%;
height: 100%;
margin: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="700" height="700"></canvas>
</body>
</html>
Just add the arc path again and use isPointInPath() with the mouse position. Only one arc can be tested at once, but it's fast to clear and add new paths. Do this in a loop.
Example
var c = document.querySelector("canvas"), ctx = c.getContext("2d");
getArc(50, 50, 40);
ctx.fill();
c.onclick = function(e) {
var rect = this.getBoundingClientRect(), // get abs. position of canvas
x = e.clientX - rect.left, // adjust mouse-position
y = e.clientY - rect.top;
getArc(50, 50, 40); // get path wo/ filling/stroking it
if (ctx.isPointInPath(x, y)) alert("Clicked");
};
function getArc(x, y, r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2);
ctx.closePath();
}
<canvas></canvas>
The other approach is to use math and trigonometry:
// at this point we have the mouse position, so:
var dx = x - arcX,
dy = y - arcY,
dist = Math.abs(Math.sqrt(dx*dx + dy*dy));
if (dist <= radius) { ...clicked... };
Tip: you can skip squaring the dist by using r2 instead.
With SVG, it would be easy - a circle is an element, and can have a click handler, and has fill that you can manipulate to change colour.
With Canvas, you need to:
save the data for each circle you draw (center and radius)
capture click on canvas as cx, cy
check every circle data x, y, r you have, see whether dx * dx + dy * dy < r * r, where dx = cx - x, dy = cy - y. Circles that satisfy this equation were clicked
repaint the circle
With Canvas, you can use function addEventListener. There are quite a few mouse events you can detect: mousedown, mouseup, mousemove, mouseout and mouseover.
Here is a example:
<!DOCTYPE HTML>
<html>
<head>
<style>
html,
body {
width: 100%;
height: 100%;
margin: 0px;
}
</style>
<script>
function initialize() {
var canvas = document.getElementById("myCanvas");
canvas.addEventListener("mousedown", doMouseDown, false);
}
function doMouseDown() {
canvas_X = event.pageX;
canvas_Y = event.pageY;
alert("X = " + canvas_X + "Y = " + canvas_Y);
}
</script>
</head>
<body>
<canvas id="myCanvas" width="700" height="700"></canvas>
</body>
</html>

Categories

Resources