I have a moving object and so it doesn't leave a trail behind I am using the clearRect(). However I can't remove everything in the canvas because that would remove my other object (which is the goal for the player to collect.)
var playerX = 350;
var playerY = 450;
function coin(posX, posY, width, height) {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'gold';
ctx.fillRect(posX, posY, width, height); //this is what I don't want to clear
}
function player() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.fillStyle = "gray";
ctx.fillRect(playerX, playerY, 50, 50);
ctx.closePath();
}
function random(min, max) {
var x = Math.floor(Math.random() * max) + min;
return x;
}
function moveLeft() {
playerX -= 5;
player();
window.requestAnimationFrame(moveLeft);
}
function moveRight() {
playerX += 5;
player();
window.requestAnimationFrame(moveLeft);
}
player();
coin(random(5, 650), random(5, 250), 50, 50);
</script>
Any help would be greatly appreciated.
One thing you can try is make a single animation function that would call itself recursively.
function animate(){
canvas.clearRect()
// draw everything here
window.requestanimationframe(animate)
}
animate()
Related
Currently, I am making a game and in need of making the image rotate toward the cursor. I am using node but the image is in a js tag in the HTML file that uses ctx to draw the image.
If I put a ctx.rotate(angle); pretty much anywhere it will rotate everything; player, map, etc. I need help so that only the player is rotated
this is a simplified version of my code:
<canvas id="ctx" width="200" height="200"></canvas>
<script>
//game
var ctx = document.getElementById("ctx").getContext("2d");
var WIDTH = 200;
var HEIGHT = 200;
var Img = {};
//player
Img.player = new Image();
Img.player.src = '/client/img/player.png';
var Player = function(/*node*/){
ctx.drawImage(Img.player, ...);
}
//map
Img.map = new Image();
Img.map.src = '/client/img/map.png';
//display everything
setInterval(function(){
ctx.clearRect(0,0,200,200);
drawMap();
for(var i in Player.list)
Player.list[i].draw();
},1000/60);
//functions
//move map so that player is always in the middle
var drawMap= function(){
var x = WIDTH/2 - Player.list[/*node*/].x;
var y = HEIGHT/2 - Player.list[/*node*/].y;
ctx.drawImage(Img.map,x,y);
}
</script>
Here's an example of what you may be looking for
const ctx = document.getElementById("ctx").getContext("2d");
const WIDTH = 500,
HEIGHT = 500;
document.getElementById("ctx").height = HEIGHT;
document.getElementById("ctx").width = WIDTH;
var Player = {
x: 50,
y: 55,
angle: 0
}
document.addEventListener("mousemove", (event) => {
var x = event.clientX - Player.x,
y = event.clientY- Player.y,
angle = Math.atan2(y,x);
Player.angle = angle
})
function draw() {
window.requestAnimationFrame(draw);
ctx.clearRect(0, 0, WIDTH, HEIGHT);
ctx.save();
ctx.translate(Player.x, Player.y);
ctx.rotate(Player.angle);
ctx.translate(-Player.x, -Player.y);
ctx.fillRect(Player.x, Player.y, 20, 20);
ctx.restore();
ctx.fillRect(150, 50, 20, 20);
}
draw();
<canvas id="ctx"></canvas>
jsfiddle here
Hope this helps!
I am trying to write a code using HTML canvas that will create a line beginning where a mousemove event occurs. The line has a defined direction and should continue extending until it is off the screen. The issue I am having is that every time I move the mouse a new line begins(this is good) but the previous line stops extending. I believe that the issue is because each new line is taking on a set of parameters with the same name as the previous line, however I am not certain that this is the issue, nor do I know how to fix it.
Here is a jsfiddle of my current code: https://jsfiddle.net/tdammon/bf8xdyzL/
I start be creating an object named mouse that takes an x and y parameter. The xbeg and ybeg will be the starting coordinates for my lines.
let canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height= window.innerHeight;
let c = canvas.getContext('2d');
let mouse ={
x:undefined,
y:undefined,
}
window.addEventListener("mousemove",function(event){
mouse.x = event.x;
mouse.y = event.y;
xbeg = mouse.x;
ybeg = mouse.y;
})
Next I create an animate function that continuously calls itself. I create a new line object which will take the xbeg and ybeg parameters for beginning points and xbeg+10 and ybeg+10 as ending point. The function then increments xbeg and ybeg. I would like this function to create new lines that do not stop extending whenever the mouse is moved.
function animate() {
requestAnimationFrame(animate);
new Line(xbeg,ybeg,xbeg+10,ybeg+10)
c.beginPath();
c.moveTo(xbeg,ybeg);
c.lineTo(xbeg+10,ybeg+10);
c.stroke();
xbeg += 1;
ybeg += 1;
}
I've added to your code an array for all your lines: let linesRy = []; and I've changed a bit your draw() function by adding this.endx++; this.endy++;
also I'm using your commented out c.clearRect(0, 0, innerWidth, innerHeight);since with every frame you redraw all the lines.
I hope this is what you need.
let linesRy = [];
let canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let c = canvas.getContext("2d");
let mouse = {
x: undefined,
y: undefined
};
let xbeg, ybeg;
window.addEventListener("mousemove", function(event) {
mouse.x = event.x;
mouse.y = event.y;
xbeg = mouse.x;
ybeg = mouse.y;
});
class Line {
constructor(begx, begy, endx, endy, dx, dy, slope) {
this.begx = begx;
this.begy = begy;
this.endx = endx;
this.endy = endy;
this.dx = endx - begx;
this.dy = endy - begy;
this.slope = dy / dx;
}
draw() {
this.endx++;
this.endy++;
c.beginPath();
c.moveTo(this.begx, this.begy);
c.lineTo(this.endx, this.endy);
c.stroke();
}
}
//let xend = 420;
//let yend = 220;
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, innerWidth, innerHeight);
linesRy.push(new Line(xbeg, ybeg, xbeg + 10, ybeg + 10, 10, 10, 1));
linesRy.forEach(l => {
l.draw();
});
}
animate();
canvas{border:1px solid;}
<canvas></canvas>
the variable c is taken local variable
function animate() {
c = canvas.getContext('2d');
requestAnimationFrame(animate);
new Line(xbeg,ybeg,xbeg+10,ybeg+10)
c.beginPath();
c.moveTo(xbeg,ybeg);
c.lineTo(xbeg+10,ybeg+10);
c.stroke();
xbeg += 1;
ybeg += 1;
}
Im trying to create and delete arcs on events, to adding parts works fine and i'm saving them in arrays so i could delete them on calling an event listener by somehow that's not happening , I mean its working fine in the console as in the array values are decremented by its not updating in the canvas
Code:
<script>
var myCanvas = document.getElementById("myCanvas");
myCanvas.width = window.innerWidth;
myCanvas.height = 500;
var c = myCanvas.getContext("2d");
var myArr = [];
myCanvas.addEventListener("click", function(){
var x = event.x;
var y = event.y;
var radius = 10;
myArr.push(new CreateCircle(x, y, radius, "#34495e"));
console.log( myArr );
});
window.addEventListener('keydown', function(){
myArr.splice(0,1);
console.log(myArr);
});
function CreateCircle(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.draw = function() {
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI*2);
c.fillStyle = this.color;
c.fill();
}
this.draw();
}
</script>
Do i need to add an delete function in the constructor function and call it on keydown event , how do i go on doing it/fixing it ?
To remove the circles, you have to clear the canvas, and then redraw it with the modified array of circles.
First of all, return an object from the CreateCircle method, so you have something to work with. There's no need for instances here.
Secondly, you could clear the canvas by resetting it's width, and then redraw based on the array, like this
var myCanvas = document.getElementById("myCanvas");
myCanvas.width = window.innerWidth;
myCanvas.height = 500;
var c = myCanvas.getContext("2d");
var myArr = [];
myCanvas.addEventListener("click", function() {
var x = event.x;
var y = event.y;
var radius = 10;
myArr.push(CreateCircle(x, y, radius, "#34495e"));
});
window.addEventListener('keydown', function() {
myArr.splice(0, 1);
myCanvas.width = myCanvas.width;
myArr.forEach(function(circle) {
CreateCircle(circle.x, circle.y, circle.r, circle.c)
})
});
function CreateCircle(x, y, radius, color) {
c.beginPath();
c.arc(x, y, radius, 0, Math.PI * 2);
c.fillStyle = color;
c.fill();
return {x: x, y: y, r: radius, c: color};
}
<canvas id="myCanvas"></canvas>
You don't update canvas anywhere. You need to create some sort of "render" function which will clear previously rendered frame and then loops through circles in array and call .draw on all of them.
Tip:
context.clearRect method is useful for clearing canvas.
I need help trying to rotate the rectangle that I have drawn on the canvas. I would like the top of the rectangle to pivot either to the right or left once I press on the arrow keys on my keyboard. This is my code so far:
HTML:
<body >
<div id="canvas-container">
<canvas id="canvas" width="500" height="400"></canvas>
</div>
</body>
CSS:
canvas {
display: inline;
}
Javascript:
document.addEventListener("DOMContentLoaded", function() {
drawBorder();
});
var canvas;
var context;
var size;
drawRectangle();
drawHalfCircle();
function drawBorder() {
canvas = document.getElementById("canvas");
context = canvas.getContext('2d');
size = {
x: canvas.width,
y: canvas.height
};
//have to set colors etc befor it is drawn
context.strokeStyle = 'black';
//takes 4 parameters
context.strokeRect(0, 0, size.x, size.y);
}
function drawRectangle() {
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.rect(246, 290, 8, 80);
ctx.stroke();
}
function drawHalfCircle(){
var c= document.getElementById("canvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.arc(250,579,308,1.2*Math.PI, 1.8*Math.PI);
ctx.stroke();
}
I have mocked something up is this along the correct lines of what you are wanting.
document.addEventListener("DOMContentLoaded", function() {
drawBorder();
});
var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
var size;
var angle = 0;
setInterval(function () {
context.save();
context.clearRect(0, 0, canvas.width, canvas.height);
drawBorder();
drawHalfCircle();
drawRectangle();
context.restore();
}, 100);
function drawBorder() {
size = {
x: canvas.width,
y: canvas.height
};
//have to set colors etc befor it is drawn
context.strokeStyle = 'black';
//takes 4 parameters
context.strokeRect(0, 0, size.x, size.y);
}
function drawRectangle() {
context.rotate(Math.PI / 180 * (angle));
context.rect(246, 290, 8, 80);
context.stroke();
}
function drawHalfCircle(){
context.beginPath();
context.arc(250,579,308,1.2*Math.PI, 1.8*Math.PI);
context.stroke();
}
document.onkeydown = function(e) {
var event = window.event ? window.event : e;
if (e.keyCode == '37') {
angle += 5;
}
else if (e.keyCode == '39') {
angle -= 5;
}
}
Basically set an interval and redraw (ie frames like in a movie) and rotate via a variable.
See a demo here
https://jsbin.com/qititacazu/edit?js,output
If you want to translate it so it will rotate around a different point do something like this.
context.translate(246, 290);
context.rotate(Math.PI / 180 * (angle));
context.rect(-4, 0, 4, 80);
I'm using Canvas to play and learn with Javascript. Currently I'm creating a circle and have it display in random areas on the screen. I was able to complete that exercise completely; everything ran smoothly in one function.
Now I would like to create an object for the circle and call it in the for loop. I created the object, but something is still wrong. I'm only seeing one circle instead of 40. I banged my head on this for awhile before coming here for help. Take a look at the code below.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
if (!ctx) {
alert('HTML5 Canvas is not supported in you browser');
}
function Circle(posX, posY, radius, startAngle, endAngle, anticlockwise) {
this.posX = posX;
this.posY = posY;
this.radius = radius;
this.startAngle = startAngle;
this.endAngle = endAngle;
this.anticlockwise = anticlockwise;
this.test = function() {
ctx.beginPath();
ctx.arc(posX, posY, radius, startAngle, endAngle, anticlockwise);
ctx.fill();
}
}
var cir = new Circle(
(Math.random() * canvas.width),
(Math.random() * canvas.height),
20,
0,
Math.PI*2,
true
);
function drawCircle() {
for(var i = 0; i < 40; i++){
cir.test();
}
}
/*setInterval(drawCircle, 400)*/
drawCircle();
You are calling cir.test() 40 times without having 40 instances of Circle. It is the same circle being drawn 40 times on top of itself.
This might be an immediate fix to your problem:
function drawCircle() {
for(var i = 0; i < 40; i++){
// Mind you that doing this
// Will not allow you to reference
// your circles after they are
// created. The best method is
// to put them in an array
// of circles
var cir = new Circle(
(Math.random() * canvas.width),
(Math.random() * canvas.height),
20,
0,
Math.PI*2,
true
);
cir.test();
}
}
/*setInterval(drawCircle, 400)*/
drawCircle();
However, I would recommend the following changes to your code:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
if (!ctx) {
alert('HTML5 Canvas is not supported in you browser');
}
function Circle(posX, posY, radius, startAngle, endAngle, anticlockwise) {
this.posX = posX;
this.posY = posY;
this.radius = radius;
this.startAngle = startAngle;
this.endAngle = endAngle;
this.anticlockwise = anticlockwise;
// Using better function names
// is always a good idea
this.testDraw = function() {
ctx.beginPath();
ctx.arc(posX, posY, radius, startAngle, endAngle, anticlockwise);
ctx.fill();
}
}
// Create an array to fill
// with Circle instances
var circlesArray = []
// Changed drawCircle to drawCircles
// it is clearer
function drawCircles() {
for(var i = 0; i < 40; i++){
// Create new Circle objects
// and add them to the circlesArray
// this will allow you to have a
// each circle later on
circlesArray.push(new Circle(
(Math.random() * canvas.width),
(Math.random() * canvas.height),
20,
0,
Math.PI*2,
true
));
// Go through each item of the array
// and call the test function
circlesArray[i].testDraw();
}
}
/*setInterval(drawCircle, 400)*/
drawCircles();
Currently your drawCircle() function is running a single test function on the same 'cir' variable 40 times. What you want to do is to fill an array with 40 new items using the for-loop. Then, use another for-loop to define those items as new Circle objects and call the test function on each new circle.
Here is the code I would use:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
if (!ctx) {
alert('HTML5 Canvas is not supported in you browser');
}
function Circle(posX, posY, radius, startAngle, endAngle, anticlockwise) {
this.posX = posX;
this.posY = posY;
this.radius = radius;
this.startAngle = startAngle;
this.endAngle = endAngle;
this.anticlockwise = anticlockwise;
this.test = function() {
ctx.beginPath();
ctx.arc(posX, posY, radius, startAngle, endAngle, anticlockwise);
ctx.fill();
}
}
/*Create an array to hold your circles*/
var circleArray = [];
function drawCircle() {
for (var i = 0; i < 40; i++) {
circleArray.push('cirlce' + i); /*Push circle variable into circleArray*/
}
for (var i = 0; i < circleArray.length; i++) {
/*Create a new circle object for every iteration of the circleArray*/
circleArray[i] = new Circle(
(Math.random() * canvas.width), (Math.random() * canvas.height),
20,
0,
Math.PI * 2,
true
);
circleArray[i].test(); /*Run the test function for every item in the circle array*/
}
}
/*setInterval(drawCircle, 400)*/
drawCircle();
<canvas id='canvas'></canvas>
Please read the comments, if you need more help understanding this just comment below.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
if (!ctx) {
alert('HTML5 Canvas is not supported in you browser');
}
//The only thing I can see perhaps changing is radius so use radius as parameter
function Circle(radius) {
this.posX = Math.random() * canvas.width; //This is always going to be the same so no need to pass as an argument
this.posY = Math.random() * canvas.height; //So will this
this.test = function() {
ctx.beginPath();
ctx.arc(this.posX, this.posY, radius, 0, Math.PI*2, true); //So will Math.PI*2, and true
ctx.fill();
}
this.test();
}
function drawCircle() {
for(var i = 0; i < 40; i++){
new Circle(i); //This passes i as the radius so you can see the differences
}
}
drawCircle();