I am making a reproduction function to my game test. Inside my newly created function contains the new wolf function and subtracts the x value of the object then draws it to the canvas. The only problem is the page remains static and nothing moves. I used MDN for my research on creating new functions. Any help or feedback would be much appreciated! Heres my code
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var body = document.getElementById("body");
var wolfPop = 2;
var bornWolves = 0;
var wolves = {
};
var funs = {
};
var name;
var fname;
function setupWolf(x, y, w, h){
context.fillStyle = "blue";
context.fillRect(wolves[name].x, wolves[name].y, wolves[name].w, wolves[name].h);
context.fill();
console.log("alive wolves: " + bornWolves);
}
body.style.overflow = "hidden";
body.style.margin = "0px";
canvas.style.backgroundColor = "black";
setInterval(function(){
if(wolfPop != bornWolves){
spawnWolf();
bornWolves++;
}
}, 1);
function spawnWolf(){
name = "w" + bornWolves;
rand = Math.floor(Math.random() * 100) + 1;
wolves[name] = Object.create({}, {x: {value: Math.floor(Math.random() * 450) + 1}, y: {value: Math.floor(Math.random() * 450) + 1}, h: {value: 10}, w: {value: 10}});
setupWolf();
var f1 = createWolfMove();
f1();
}
function createWolfMove(){
console.log("called");
return new Function('var k = wolves[name]; setInterval(function(){ k.x -= 1; context.fillStyle = "cornflowerblue"; context.fillRect(k.x, k.y, k.w, k.h); context.fill();}, 100);');
}
<body id="body">
<canvas id="canvas" height="500px" width="500px"></canvas>
</body>
Youre probably looking for inheritance :
You could create new wolves that inherit from a wolf class:
//setup canvas
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var body = document.getElementById("body");
body.style.overflow = "hidden";
body.style.margin = "0px";
canvas.style.backgroundColor = "black";
var wolfPop = 2;
var bornWolves = 0;
var wolves = [];
function rand(a,b=1){return Math.floor(Math.random() * a) + b;}
//constructor
function Wolf(name,x,y,w,h){
//setup
this.name=name||" w"+bornWolves;
this.x=x||rand(450);
this.y=y||rand(450);
this.w=w||10;
this.h=h||10;
//update globals
wolves.push(this);
bornWolves++;
}
Wolf.prototype={
update:function(){
context.fillStyle = "blue";
context.fillRect(this.x, this.y, this.w, this.h);
},
moving:false,
move:function(){
this.x+=rand(100,-50);//move between 50 and -50
this.y+=rand(100,-50);/
}
};
setInterval(function(){
//clear
context.clearRect(0, 0, canvas.width, canvas.height);
//update all wolves
wolves.forEach(function(wolf){
if(wolf.moving) wolf.move();
wolf.update();
}
if(wolfPop != bornWolves){
new Wolf();
}
}, 1);
//add a new wolf
var first=new Wolf(false,false,20,20);// a bit fater
first.moving=true;
Related
I am making canvas creation by for loop.
Each 20 circles wihch has each different size shows up every second.
I need to stop/escape loop when the total of circles becomes 100.
I tried to stop interval like below. However, it continues looping in console even though the shape of circle stops showing up.
if (circles.length > 100) {
console.log('STOP');
return;
}
Is there any way?
Thank you.
class circle {
constructor() {
this.x = 0;
this.y = 0;
this.r = 0;
}
}
const canvas = document.getElementById('canvas');
const context = canvas.getContext("2d");
let colors = ["#96ceb4","#ffeead","#ff6f69","#ffcc5c","#88d8b0"];
let circles = new Array();
window.addEventListener('load', function(){
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
context.clearRect( 0, 0, canvas.width, canvas.height );
function draw() {
for (let i=0; i < 20; i++) { //20 blocks at a time
const item = new circle();
item.x = Math.floor(Math.random()*canvas.width);
item.y = Math.floor(Math.random()*canvas.height);
item.r = Math.floor(Math.random()*50);
circles.push(item);
console.log(circles.length);
if (circles.length > 100) {
console.log('STOP');
return;
}
context.beginPath();
context.fillStyle=colors[Math.floor(Math.random()*colors.length)];
context.globalAlpha=0.5;
context.arc(item.x, item.y, item.r, 0, Math.PI*2, true);
context.fill();
};
};
setInterval(draw, 1000);
});
body {overflow: hidden;}
<canvas id="canvas"></canvas>
You need to use the setInterval return to get the id to clear.
class circle {
constructor() {
this.x = 0;
this.y = 0;
this.r = 0;
}
}
var timer;
function stopTimer(){
clearInterval(timer);
}
const canvas = document.getElementById('canvas');
const context = canvas.getContext("2d");
let colors = ["#96ceb4","#ffeead","#ff6f69","#ffcc5c","#88d8b0"];
let circles = new Array();
window.addEventListener('load', function(){
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
context.clearRect( 0, 0, canvas.width, canvas.height );
function draw() {
for (let i=0; i < 20; i++) { //20 blocks at a time
const item = new circle();
item.x = Math.floor(Math.random()*canvas.width);
item.y = Math.floor(Math.random()*canvas.height);
item.r = Math.floor(Math.random()*50);
circles.push(item);
console.log(circles.length);
if (circles.length > 100) {
console.log('STOP');
stopTimer();
return;
}
context.beginPath();
context.fillStyle=colors[Math.floor(Math.random()*colors.length)];
context.globalAlpha=0.5;
context.arc(item.x, item.y, item.r, 0, Math.PI*2, true);
context.fill();
};
};
timer = setInterval(draw, 1000);
});
body {overflow: hidden;}
<canvas id="canvas"></canvas>
I am having problems when drawing a circle. How do I clear it?
I also still want to maintain the transparent background as much as possible as I am planning on making particles rain down. I also would want to not use images to lower the load on the server.
var canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");
const ParticleFactory = function(){
this.interval = 100;
this.lastOutput = Date.now();
this.particles = [];
}
ParticleFactory.prototype.tick = function(){
if (Date.now() > this.lastOutput + this.interval) {
const particle = new Particle(500, 100, 4);
this.particles.push(particle);
this.lastOutput = Date.now();
}
for (var i=0; i < this.particles.length; i++) {
this.particles[i].tick();
};
}
ParticleFactory.prototype.draw = function(){
for (var i=0; i < this.particles.length; i++) {
this.particles[i].draw();
};
}
ParticleFactory.prototype.del = function(toDelete){
this.particles = this.particles.filter(item => item !== toDelete);
}
const Particle = function(x, y, r){
this.x = x;
this.y = y;
this.r = r;
}
Particle.prototype.tick = function(){
this.x -= 0.1;
}
Particle.prototype.draw = function(){
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
ctx.fillStyle = "rgb(0, 0, 255)";
ctx.fill();
ctx.closePath();
}
// Definitions
let particleFactory = new ParticleFactory;
function draw(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
particleFactory.draw();
}
function tick(){
particleFactory.tick();
draw()
window.requestAnimationFrame(tick)
}
document.addEventListener("DOMContentLoaded", function() {
tick();
});
ctx.clearRect() doesn't clear the curcle that is being draws every tick by Particle.draw()
The dot moves and leaves a trail behind even when ctx.clearRect() is run before every draw.
Using NodeJS and Socket.io, I'm making a quick canvas app that moves a shape across the screen. This data will appear on all clients. Each square is timestamped to determine draw order.
Below is client.html. It says that I "cannot set property lastUpdate" of undefined. How is it considered undefined? I tried defining it so many times at the top. What's wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<script src="/socket.io/socket.io.js"></script>
<script>
"use strict";
var canvas;
var ctx;
var socket;
//var lastUpdate = new Date().getTime();
/*var square = {
lastUpdate: new Date().getTime(),
x: 0,
y: 0,
height: 100,
width: 100
};*/
//
//var person = {name: 'user' + (Math.floor((Math.random() * 1000)) + 1)};
//var user = 'user' + (Math.floor((Math.random() * 1000)) + 1);
//var user = Object.keys(something about name);
//var user = Object.keys(user);
//function person(name) {
//this.name = name;
//}
//var user = Object.keys(person);
//lets try using a prototype
/*function user(lastUpdate, x, y, width, height) {
this.lastUpdate = lastUpdate;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}*/
var name = {lastUpdate: new Date().getTime(), x: 0, y: 0, width: 100, height: 100};
var user = Object.keys(name);
var draws = {};
function updatePosition() {
var message = {
xUpdate: 10,
yUpdate: 5
}
socket.emit('movementUpdate', message);
}
/*function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(square.x, square.y, square.width, square.height);
}*/
//
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
var keys = Object.keys(draws);
for(var i = 0; i < keys.length; i++)
{
var drawCall = draws[keys[i]];
//order to draw
//gets drawcalls instead of var square
ctx.fillRect(drawCall.x, drawCall.y, drawCall.width, drawCall.height);
}
}
//
function setup() {
var time = new Date().getTime();
//console.log(time);
var x = Math.floor(Math.random()*(300-10) + 10); //random x position
var x = Math.floor(Math.random()*(300-10) + 10); //random y position
draws[user] = {lastUpdate: time, x: x, y: y, width: 100, height: 100};
}
/*function update(data) {
square = data;
redraw();
}*/
//
function handleMessage(data) {
if(!draws[data.name])
{
draws[data.name] = data.coords;
}
else if(data.coords.lastUpdate > draws[data.name].lastUpdate)
{
draws[data.name] = data.coords;
}
draw(); //redraw after updates
}
function init() {
canvas = document.querySelector("#canvas");
ctx = canvas.getContext("2d");
socket = io.connect();
socket.on('connect', function () {
//setInterval(updatePosition, 1000);
setInterval(function()
{
var time = new Date().getTime();
//console.log(time);
console.log(draws);
**draws[user].lastUpdate = time; //lastUpdate is UNDEFINED**
draws[user].x += 5;
socket.emit('draw', {name: user, coords: draws[user]});
draw();
}, 3000);
});
socket.on('updatedDraw', handleMessage);
//socket.on('updatedMovement', updatePosition); //UNDEFINED, used to be 'update'. Could it be 'handleMessage'?
}
window.onload = init;
</script>
</head>
<body>
<canvas id="canvas" height="500" width="500">Please use an HTML 5 browser</canvas>
</body>
</html>
I am working on my javascript after a foray into the land of Java and have encountered a problem. I have a constructor which gives each object the method this.move() and adds their names to an array. I would like to call each of the methods this.move() that are held by the objects in the array but I cannot come up with a way to. My code is below.
var arrballs = [];
var x;
var y;
var radius;
var speed = 1;
var startup = function startup() {
var canvas1 = document.getElementById("canvas1");
var context = canvas1.getContext("2d");
context.fillStyle = "rgb(0, 0, 0)";
context.fillRect(0, 0, 500, 500);
var ball_1 = new ball(5, 0, 100, 100, 2);
}
var ball = function(radius, heading, xposition, yposition, speed) { //constructor for balls
this.radius = radius;
this.heading = heading; //in standard polar
this.xposition = xposition;
this.yposition = yposition;
this.move = function move() {
this.xposition = Math.cos(this.heading)*speed + this.xposition //converts the heading to a unit vector and multiplies it by the scaler speed value
this.yposition = Math.sin(this.heading)*speed + this.yposition
}
arrballs[arrballs.length] = "ball_" + arrballs.length + 1;
}
function drawScreen() {
var canvas1 = document.getElementById("canvas1");
var context = canvas1.getContext("2d");
context.clearRect(0,0,500,500);
for (i=0; i<arrballs.length; i++) {
arrballs[i].move();
context.beginPath();
context.fillStyle = "red";
context.arc(arrballs[i].xposition, arrballs[i].yposition, radius, 0, 2*Math.PI, false);
context.fill();
context.closePath();
}
}
Apologies for the spacing, it got eaten by the copypaste monster.
Thanks in advance for any help.
I'm a newbie to HTML, CSS and JS. Currently I'm working on JavaScript to create a pie chart. My doubt is how can I include a CSS hover function within a function.
Can anyone help me include CSS hover inside a function in the JavaScript code below?
<script type="text/javascript">
function PieChart(id, o) {
this.includeLabels = true;
if (o.includeLabels == undefined) {
this.includeLabels = false;
}
else {
this.includeLabels = o.includeLabels;
}
this.data = o.data ? o.data : [30, 70, 45, 65, 20, 130];
this.labels = o.labels ? o.labels : ["First", "Second", "Third", "Fourth", "Fifth", "Sixth"];
this.colors = o.colors ? o.colors : [
["#bbddb3", "#1d8e04"], // green
["#e2f5b4", "#9edd08"], // yellow green
["#fdfbb4", "#faf406"], // yellow
["#fbd4b7", "#f2700f"], // orange
["#f8bdb4", "#ea2507"], // red
["#e2bcbd", "#9e2126"] // purple
];
this.canvas = document.getElementById(id);
}
PieChart.prototype = {
select: function(segment) {
var self = this;
var context = this.canvas.getContext("2d");
this.drawSegment(this.canvas, context, segment, this.data[segment], true, this.includeLabels);
},
draw: function() {
var self = this;
var context = this.canvas.getContext("2d");
for (var i = 0; i < this.data.length; i++) {
this.drawSegment(this.canvas, context, i, this.data[i], true, this.includeLabels);
}
},
drawSegment: function(canvas, context, i, size, isSelected, includeLabels) {
var self = this;
context.save();
var centerX = Math.floor(canvas.width / 2);
var centerY = Math.floor(canvas.height / 2);
radius = Math.floor(canvas.width / 2);
var startingAngle = self.degreesToRadians(self.sumTo(self.data, i));
var arcSize = self.degreesToRadians(size);
var endingAngle = startingAngle + arcSize;
context.beginPath();
context.moveTo(centerX, centerY);
context.arc(centerX, centerY, radius, startingAngle, endingAngle, false);
context.closePath();
isSelected ?
context.fillStyle = self.colors[i][1] :
context.fillStyle = self.colors[i][0];
context.fill();
context.restore();
if (includeLabels && (self.labels.length > i)) {
self.drawSegmentLabel(canvas, context, i, isSelected);
}
},
drawSegmentLabel: function(canvas, context, i, isSelected) {
var self = this;
context.save();
var x = Math.floor(canvas.width / 2);
var y = Math.floor(canvas.height / 2);
var angle = self.degreesToRadians(self.sumTo(self.data, i));
context.translate(x, y);
context.rotate(angle);
context.textAlign = 'center';
var fontSize = Math.floor(canvas.height / 25);
context.font = fontSize + "pt Helvetica";
var dx = Math.floor(canvas.width * 0.5) - 100;
var dy = Math.floor(canvas.height * 0.05);
context.fillText(self.labels[i], dx, dy+dy);
alert(self.labels[i]);
context.restore();
},
drawLabel: function(i) {
var self = this;
var context = this.canvas.getContext("2d");
var size = self.data[i];
self.drawSegmentLabel(this.canvas, context, i, size, true);
},
degreesToRadians: function(degrees) {
return (degrees * Math.PI)/180;
},
sumTo: function(a, i) {
var sum = 0;
for (var j = 0; j < i; j++) {
sum += a[j];
}
return sum;
}
}
</script>
create style element and write some style rules.
var styleEl = document.createElement('style');
styleEl.innerHTML = 'body{color:blue; ... other styles}';
document.head.appendChild(styleEl);
set cssText, new rules will rewrite olds;
document.body.style.cssText = 'color:#abcdef;';
set style dierectly
document.body.style.color = 'black';
there may be some other tricks.
I would recommend you start with jQuery as it is much easier to use than plain JavaScript and DOM manipulation.
Take a look at the hover event and the css() function.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").hover(function(){
$("p").css("color","red");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>