can't use function more than once - javascript

For some reason i can't seem to be able use my "player" function more than once so it means i can't update it's positioning can anyone help and explain why?
heres my code:
var gridHeight = 1000, gridWidth = 1000, canvasHeight = 250, canvasWidth = 250, p = 0;
var currentPositionX = 0;
var currentPositionY = 0;
function buildGrid() {
$("body").append("<canvas></canvas").css({
height: canvasHeight,
width: canvasWidth,
border: "2px solid #000"
});
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
$("#canvas").css({height: canvasHeight, width: canvasWidth});
for (var x = 0; x <= gridWidth; x += 40) {
context.moveTo(0.5 + x + p, p);
context.lineTo(0.5 + x + p, gridHeight + p);
}
for (var x = 0; x <= gridHeight; x += 20) {
context.moveTo(p, 0.5 + x + p);
context.lineTo(gridWidth + p,x + p);
}
context.strokeStyle = "black";
context.stroke();
function player(x, y, w, h, c) {
this.x = x || 0;
this.y = y || 0;
this.h = h || 20;
this.w = w || 40;
this.c = c || "#FF0000";
}
function draw() {
player = new player();
context.fillstyle = player.c;
context.fillRect(player.x,player.y,player.w,player.h);
$("#right").on("click", function() {
player.x += player.w;
return player.x;
})
}
setInterval(draw, 500)
}
$(document).ready(function() {
buildGrid();
})
* {
padding: 0px;
margin: 0px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/game.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="scripts/game.js"></script>
</head>
<body style=" background: lightblue;">
<canvas id="canvas"></canvas>
<div id="controls">
<button class="control" id="up">Up</button>
<button class="control" id="left">Left</button>
<button class="control" id="down">Down</button>
<button class="control" id="right">Right</button>
<button class="control" id="newPlayer">new player</button>
</div>
</body>
</html>
Can anyone help? My aim is make the buttons move the square around the grid. But also it have inheritable properties for further functionality late on.

player = new player(); you overwrite your function definition with the result of its execution in draw().
If you just add var in front of this line, the player var will be restricted to the scope of draw(), which might be what you want.

jsFiddle : https://jsfiddle.net/j2q2qn2e/
snippet of javascript
function player(x, y, w, h, c) {
this.x = x || 0;
this.y = y || 0;
this.h = h || 20;
this.w = w || 40;
this.c = c || "#FF0000";
}
player = new player();
...
function draw() {
context.fillstyle = player.c;
context.fillRect(player.x,player.y,player.w,player.h);
}
setInterval(draw, 3)
Basically you where creating a new player per draw, but what I have done is moved your player "class" outside of your calling functions and created it outside so we can create one basic player. I also moved your
$("#right").on("click", function() {
player.x += player.w;
return player.x;
});
to inside the jQuery doc ready because it needs to assign the event here not inside of your draw function or you would be adding multiple event listeners. So you can now use your right button correctly.

Related

Selecting and deselecting drawn objects on canvas and moving to mouse X and Y

The attached code shows how to select (on click) a drawn object on canvas and then the object is moved with a double click to click position or deselected with a double click prior to/ post-movement.
I have tried for days but could not work out how to apply this function to all objects in a class or an array via looping (via class constructor + prototyping). I would like to be able to select or deselect any object on screen.
Help will be very much appreciated. Thank you.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
canvas {
display: block;
margin: 0px;
}
body {
margin: 0px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<input id="click1" type ="button" value="x" style="position: fixed; top: 0px; left: 650px; position: absolute;"></input>
<input id="click2" type ="button" value="y" style="position: fixed; top: 0px; left: 750px; position: absolute;"></input>
<script>
window.onload = function(){
var canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;
let strokeColor;
let color;
let mouse_x;
let mouse_y;
let x;
let y;
let w;
let h;
let selected = false;
x = 50;
y = 50;
w = 50;
h = 50;
color="green";
strokeColor = "green";
document.getElementById('canvas').addEventListener("mousemove",go);
document.getElementById('canvas').addEventListener("mouseup",mouseUp);
document.getElementById('canvas').addEventListener("dblclick",dblClick);
document.getElementById('canvas').addEventListener("dblclick",move);
function move(){
if(selected == true){
x = mouse_x;
y = mouse_y;
}
}
function mouseUp(){
if(mouse_x > x && mouse_x < x+w && mouse_y > y && mouse_y < y+w){
strokeColor = "black";
selected = true;
console.log(selected);
}
}
function dblClick(){
if(mouse_x > x && mouse_x < x+w && mouse_y > y && mouse_y < y+w){
color = "green";
strokeColor = color;
selected = false;
console.log(selected);
}
}
function go(e){
mouse_x = e.clientX;
mouse_y = e.clientY;
document.getElementById('click1').value = mouse_x;
document.getElementById('click2').value = mouse_y;
}
function draw(){
context.strokeStyle = strokeColor;;
context.fillStyle = color;
context.beginPath();
context.lineWidth = 3;
context.rect(x,y,w,h);
context.fill();
context.stroke();
}
function animate(){
context.clearRect(0,0,width,height);
context.save();
draw();
context.restore();
requestAnimationFrame(animate);
}
animate();
};
</script>
</body>
</html>
This should be easy to do, let's first talk about the logic that we need.
Have a list of items that we can draw.
Make those items have their own state.
Check if when we click we hit an item or not.
Move or toggle the selected item.
Handle Clear & Draw of the canvas.
Made this simple fiddle just to show you the idea behind it,
let context = $("canvas")[0].getContext("2d");
let elements = [
new element(20, 20, 20, 20, "green"),
new element(45, 30, 30, 30, "red"),
new element(80, 40, 50, 50, "blue"),
];
let mousePosition = {
x: 0,
y: 0,
};
let selected;
function element(x, y, height, width, color) {
this.x = x;
this.y = y;
this.height = height;
this.width = width;
this.color = color;
this.selected = false;
this.draw = function(context) {
context.strokeStyle = (this.selected ? "black" : "white");
context.fillStyle = this.color;
context.beginPath();
context.lineWidth = 2;
context.rect(this.x, this.y, this.height, this.width);
context.fill();
context.stroke();
}
this.move = function(x, y) {
this.x = x;
this.y = y;
}
}
//Select Function
function get_select(x, y) {
let found;
$.each(elements, (i, element) => {
if(x > element.x
&& x < element.x + element.width
&& y > element.y
&& y < element.y + element.height) {
found = element;
}
});
return (found);
}
// Handle selection & Movement.
$("canvas").click(function() {
let found = get_select(mousePosition.x, mousePosition.y);
Clear();
// Toggle Selection
if (found && !selected) {
found.selected = true;
selected = found;
} else if (found === selected) {
found.selected = false;
selected = null;
}
// Move
if (!found && selected) {
selected.move(mousePosition.x, mousePosition.y);
}
Draw();
});
// Record mouse position.
$("canvas").mousemove((event) => {
mousePosition.x = event.pageX;
mousePosition.y = event.pageY;
});
//Draw ALL elements.
function Draw() {
$.each(elements, (i, element) => {
element.draw(context);
});
}
function Clear() {
context.clearRect(0, 0, $("canvas")[0].width, $("canvas")[0].height);
}
// Start.
$(document).ready(() => {
Draw();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<canvas></canvas>
</body>
</html>
Hope it helps you out!

Javascript subroutines don't run

So I am new to javascript and a beginner programmer. I know the initialization subroutine always go first. I don't get why the subroutines aren't running. And I was wondering if any variables in the initialization subroutine can be used in any other subroutines. I am trying to make a program using Bresenham Line Algorithm.
<html>
<head>
<body>
<canvas id="canvas" width="500" height="500" style="border: 1px solid black;" onclick="coordinates(event)">></canvas>
</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
intialization();
drawGrid();
mouseClick();
//Intialization--------------------------------
//Intialization--------------------------------
function intialization() {
var cnv = document.getElementById("canvas");
var Width = cnv.width;
var Height = cnv.height;
var ctx = cnv.getContext('2d');
var click_counter = 0; //switching between storing first and second point coordinates
p1x = 0; //stores user's click on canvas
p1y = 0; //stores user's click on canvas
p2x = 0; //stores user's click on canvas
p2y = 0; //stores user's click on canvas
}
//Intialization--------------------------------
//GRID---------------------------------
function drawGrid() {
var gridLines = {
Lines: {
space: 10,
// color: "'#xxxxxx'"
}
};
drawGridLines(cnv, gridLines.Lines);
return;
}
function drawGridLines(cnv, lineOptions) {
ctx.strokeStyle = lineOptions.color;
ctx.strokeWidth = 1;
ctx.beginPath();
var counter = null;
var i = null;
var x = null;
var y = null;
counter = Math.floor(Width / lineOptions.space);
for (i = 1; i <= counter; i++) {
x = (i * lineOptions.space);
ctx.moveTo(x, 0);
ctx.lineTo(x, Height);
ctx.stroke();
}
counter = Math.floor(Height / lineOptions.space);
for (i = 1; i <= counter; i++) {
y = (i * lineOptions.space);
ctx.moveTo(0, y);
ctx.lineTo(Width, y);
ctx.stroke();
}
ctx.closePath();
return;
}
//GRID---------------------------------
//MOUSE---------------------------------
function mouseClick {
if (click_counter = 0) {
function coordinates(event) {
var x1 = event.offsetX;
var y1 = event.offsetY;
p1x = x1;
p1y = y1;
console.log("x coords: " + p1x + ", y coords: " + p1y);
} else
function coordinates(event) {
var x1 = event.offsetX;
var y1 = event.offsetY;
p2x = x1;
p2y = y1;
console.log("x coords: " + p2x + ", y coords: " + p2y);
}
}
//MOUSE---------------------------------
//MOUSE---------------------------------
</script>
</head>
</html>
Your initialization and drawGrid functions are being called before the document is even loaded so this will fail. You should use the jquery method-
$(document).ready(function(){
//callyour functions here
})
Another issue you have is that you are trying to use variables which are out of scope. Like cnv for example. You should declare a object like canvas at the top of your js:
canvas = {}
and add all of the variables you want to share to this. for instance :
canvas.cnv = document.getElementById("canvas");
canvas.Width = canvas.cnv.width;
canvas.Height = canvas.cnv.height;
canvas.ctx = canvas.cnv.getContext('2d');
Here is a simple example of how to use the canvas:
<html>
<head>
<script src="index.js"></script>
<body>
<canvas id="canvas" width="500" height="500" style="border: 1px solid black;" onmousemove="mouseClick(event)">></canvas>
</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
canvas = {}
var isMouseDown = false;
document.addEventListener('mousedown', function(event) {
if ( event.which ) isMouseDown = true;
}, true);
document.addEventListener('mouseup', function(event) {
if ( event.which ) isMouseDown = false;
}, true);
$(document).ready(function(){
canvas.cnv = document.getElementById("canvas");
canvas.Width = canvas.cnv.width;
canvas.Height = canvas.cnv.height;
canvas.ctx = canvas.cnv.getContext('2d');
});
function mouseClick(e) {
console.log(isMouseDown)
if (isMouseDown){
var x1 = event.offsetX;
var y1 = event.offsetY;
canvas.ctx.lineTo(x1, y1);
canvas.ctx.stroke();
}
}
</script>
</head>
</html>

HTML Canvas & JavaScript - Scale Object on Hover

The script below draws 4 curved rectangles and detects if they are hovered over or clicked on with mouseup and mousemove event listeners. When one of the rectangles is hovered over, I would like it to grow slightly over the course of a second - it should then shrink back when the cursor moves off the rectangle.
The problem I have is that the only way I can think of doing this is by writing a function inside the if (this.selected) { clause which plots a new version of the rectangle for each frame in an animation lasting a second, but this clause is inside the function that plots a new version of the rectangle itself! How, then, can I write a function outside of curvedRect.prototype.makeCurvedRect which only runs when the cursor is over one of the rectangles? Any help will be appreciated.
var c=document.getElementById('game'),
canvasX=c.offsetLeft,
canvasY=c.offsetTop,
ctx=c.getContext('2d');
var curvedRect = function(id, x, y, w, h) {
this.id = id;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.selected = false;
}
curvedRect.prototype.makeCurvedRect = function() {
ctx.beginPath();
ctx.lineWidth='8';
ctx.strokeStyle='white';
ctx.moveTo(this.x+10, this.y);
ctx.lineTo(this.x+this.w-10, this.y);
ctx.quadraticCurveTo(this.x+this.w, this.y, this.x+this.w, this.y+10);
ctx.lineTo(this.x+this.w, this.y+this.h-10);
ctx.quadraticCurveTo(this.x+this.w, this.y+this.h, this.x+this.w-10, this.y+this.h);
ctx.lineTo(this.x+10, this.y+this.h);
ctx.quadraticCurveTo(this.x, this.y+this.h, this.x, this.y+this.h-10);
ctx.lineTo(this.x, this.y+10);
ctx.quadraticCurveTo(this.x, this.y, this.x+10, this.y);
ctx.stroke();
if (this.selected) {
// BM67 edit By Blindman67 removed annoying alert and replaced it with console.log
// As I did not want to add elsewhere to the code to declare hoverMessageShown is safely declared here to stop the console repeating the message.
if(window["hoverMessageShown"] === undefined){
window["hoverMessageShown"] = true;
console.log('When hovered over, I would like this box to grow slightly over a short period of time (say a second). When the mouse is removed I would like it to shrink back.')
}
// BM67 end.
}
}
curvedRect.prototype.hitTest = function(x, y) {
return (x >= this.x) && (x <= (this.w+this.x)) && (y >= this.y) && (y <= (this.h+this.y));
}
var Paint = function(element) {
this.element = element;
this.shapes = [];
}
Paint.prototype.addShape = function(shape) {
this.shapes.push(shape);
}
Paint.prototype.render = function() {
this.element.w = this.element.w;
for (var i=0; i<this.shapes.length; i++) {
this.shapes[i].makeCurvedRect();
}
}
Paint.prototype.setSelected = function(shape) {
for (var i=0; i<this.shapes.length; i++) {
this.shapes[i].selected = this.shapes[i] == shape;
}
this.render();
}
Paint.prototype.select = function(x, y) {
for (var i=this.shapes.length-1; i >= 0; i--) {
if (this.shapes[i].hitTest(x, y)) {
return this.shapes[i];
}
}
return null
}
var paint = new Paint(c);
var img1 = new curvedRect('1', 200, 55, 150, 150);
var img2 = new curvedRect('2', 375, 55, 150, 150);
var img3 = new curvedRect('3', 200, 230, 150, 150);
var img4 = new curvedRect('4', 375, 230, 150, 150);
paint.addShape(img1);
paint.addShape(img2);
paint.addShape(img3);
paint.addShape(img4);
paint.render();
function mouseUp(event) {
var x = event.x - canvasX;
var y = event.y - canvasY;
var shape = paint.select(x, y);
if (shape) {
alert(shape.id);
}
// console.log('selected shape: ', shape);
}
function mouseMove(event) {
var x = event.x - canvasX;
var y = event.y - canvasY;
var shape = paint.select(x, y);
paint.setSelected(shape);
}
c.addEventListener('mouseup', mouseUp);
c.addEventListener('mousemove', mouseMove);
canvas {
display: block;
margin: 1em auto;
border: 1px solid black;
background: #FF9900;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>uTalk Demo</title>
<link rel='stylesheet' type='text/css' href='game.css' media='screen'></style>
</head>
<body>
<canvas id="game" width = "750" height = "500"></canvas>
</body>
</html>
Change the makeCurvedRect method to something like this:
var c=document.getElementById('game'),
canvasX=c.offsetLeft,
canvasY=c.offsetTop,
ctx=c.getContext('2d');
var curvedRect = function(id, x, y, w, h) {
this.id = id;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.selected = false;
}
curvedRect.prototype.makeCurvedRect = function() {
var delta = this.selected?10:0 ;
var x = this.x - delta;
var y = this.y - delta;
var w = this.w + (2*delta);
var h = this.h + (2*delta);
ctx.beginPath();
ctx.lineWidth='8';
ctx.strokeStyle='white';
ctx.moveTo(x+10, y);
ctx.lineTo(x+ w -10, y);
ctx.quadraticCurveTo(x + w, y,x + w,y + 10);
ctx.lineTo( x + w, y + h-10);
ctx.quadraticCurveTo( x + w, y + h, x + w - 10, y + h);
ctx.lineTo(x + 10,y + h);
ctx.quadraticCurveTo( x, y + h, x, y+h-10);
ctx.lineTo(x, y+10);
ctx.quadraticCurveTo(x, y, x+10, y);
ctx.stroke();
}
curvedRect.prototype.hitTest = function(x, y) {
return (x >= this.x) && (x <= (this.w+this.x)) && (y >= this.y) && (y <= (this.h+this.y));
}
var Paint = function(element) {
this.element = element;
this.shapes = [];
}
Paint.prototype.addShape = function(shape) {
this.shapes.push(shape);
}
Paint.prototype.render = function() {
this.element.width = this.element.width;
for (var i=0; i<this.shapes.length; i++) {
this.shapes[i].makeCurvedRect();
}
}
Paint.prototype.setSelected = function(shape) {
for (var i=0; i<this.shapes.length; i++) {
this.shapes[i].selected = this.shapes[i] == shape;
}
this.render();
}
Paint.prototype.select = function(x, y) {
for (var i=this.shapes.length-1; i >= 0; i--) {
if (this.shapes[i].hitTest(x, y)) {
return this.shapes[i];
}
}
return null
}
var paint = new Paint(c);
var img1 = new curvedRect('1', 200, 55, 150, 150);
var img2 = new curvedRect('2', 375, 55, 150, 150);
var img3 = new curvedRect('3', 200, 230, 150, 150);
var img4 = new curvedRect('4', 375, 230, 150, 150);
paint.addShape(img1);
paint.addShape(img2);
paint.addShape(img3);
paint.addShape(img4);
paint.render();
function mouseUp(event) {
var x = event.x - canvasX;
var y = event.y - canvasY;
var shape = paint.select(x, y);
if (shape) {
alert(shape.id);
}
// console.log('selected shape: ', shape);
}
function mouseMove(event) {
var x = event.x - canvasX;
var y = event.y - canvasY;
var shape = paint.select(x, y);
paint.setSelected(shape);
}
c.addEventListener('mouseup', mouseUp);
c.addEventListener('mousemove', mouseMove);
canvas {
display: block;
margin: 1em auto;
border: 1px solid black;
background: #FF9900;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>uTalk Demo</title>
<link rel='stylesheet' type='text/css' href='game.css' media='screen'></style>
</head>
<body>
<canvas id="game" width = "750" height = "500"></canvas>
</body>
</html>

How to move an animated line in html 5 canvas?

I have this animated line that I am building using HTML5 Canvas class. I am trying to move the line to the left when I hit up left button. I am still new to web development and just started messing around with HTML and JS. Therefore, I request you to help me out. Please explain in detail so I can learn what I am doing wrong! Thanks! I have this following code
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
<button type="button" id="startButton">Start</button>
<button type="button" id="left">Left</button>
<button type="button" id="left">Right</button>
<script>
(function(){
function init(){
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
var direction=0;
canvas.width = 200;
canvas.height = 200;
var points = [],
currentPoint = 20000,
nextTime = new Date().getTime()+500,
pace = 200;
var startingx=25,startingy=0;
// make some points
for (var i = 0; i < canvas.height ; i++) {
for (var k = 0; k < canvas.width ; k++){
points.push({
x: i ,
y: k
});
}
}
function draw(){
if(new Date().getTime() > nextTime){
nextTime = new Date().getTime() + pace;
currentPoint++;
}
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(points[20000].x, points[20000].y);
ctx.lineWidth = 2;
ctx.strokeStyle = '#FF0000';
ctx.fillStyle = '#FF0000';
for (var p = 20000, plen = currentPoint; p < plen; p++) {
if(direction==0)
{ctx.lineTo(points[p].x, points[p].y);ctx.stroke();}
else if(direction==1)
{ctx.lineTo(points[p+200].x, points[p+200].y);ctx.stroke();}
else if(direction==2)
{ctx.lineTo(points[p-2].x, points[p-2].y);ctx.stroke();}
else if(direction==3)
{ctx.lineTo(points[p-200].x, points[p-200].y);
ctx.stroke();}
}
cancelMe = requestAnimationFrame(draw);
}
function startAnimation(event){
if(this.textContent === "Start"){
requestAnimationFrame(draw);
this.textContent = 'Pause';
}
else{
cancelAnimationFrame(cancelMe);
this.textContent = 'Start';
}
}
function leftTurn(event){
direction++;
if(direction>3)
{
direction=0;
}
}
function rightTurn(event){
direction--;
if(direction<0)
{
direction=3;
}
}
var startButton = document.getElementById('startButton');
startButton.addEventListener('click',startAnimation,false);
var leftButton = document.getElementById('left');
var rightButton = document.getElementById('right');
leftButton.addEventListener('click',leftTurn,false);
rightButton.addEventListener('click',rightTurn,false);
}
//invoke function init once document is fully loaded
window.addEventListener('load',init,false);
}()); //self invoking function
</script>
</body>
</html>

Keep track and display arrival order of array elements after animation ends in JavaScript

So, I have created an array of 10 blocks(rectangles) that move horizontally towards a "finish" line (end of canvas width) with variable speeds. I'm looking for a way to keep track of the arrival order of each array element and display it on top of each rectangle as it stops moving. I've tried using a counter and the fillText method to do that, but it only works until other elements come to a full stop and then it replaces the order. For a better view of what happens, here is my code. If anyone has any suggestions on what to use in order to fulfill my goal, it is very much appreciated. Keep in mind that I only use plain JavaScript as in no jQuery or other frameworks as I am learning the basics. Thanks in advance.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cars</title>
<style>
canvas {
border:1px solid #3D0404;
}
h2 {
margin-left:23%;
}
</style>
<script>
var c;
var ctx;
var cars = [];
var width = 100;
var height = 100;
var x = 0;
var y = 0;
var i;
var temp;
var cw = 1000;
var ch = 1000;
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
function init() {
c = document.getElementById("myCanvas");
ctx = c.getContext("2d");
pushCar();
}
function CreateCar(x,y,width,height,speed){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.speed = speed;
}
function pushCar(){
for (var i=0; i<10; i++){
var speed = Math.random() * 10;
var car = new CreateCar(x,y,width,height,speed);
cars.push(car);
y += 100;
}
drawAll();
}
function clear (){
ctx.clearRect (0,0,cw,ch);
}
function draw(cars){
ctx.beginPath();
ctx.fillStyle = "#f00";
ctx.fillRect(temp.x, temp.y, width, height);
ctx.strokeStyle = "#000";
ctx.outlineWidth = 2;
ctx.strokeRect(temp.x, temp.y, width, height);
ctx.closePath();
}
function drawAll(){
clear();
var z = 1;
for (var i=0; i<cars.length; i++){
temp = cars[i];
draw(temp);
if (temp.x+100 < c.width){
temp.x += temp.speed;
}else {
ctx.font = "20pt Verdana";
ctx.fillStyle = "#000";
ctx.fillText(z, 950, temp.y+55);
z++;
}
}
requestAnimFrame(drawAll, c);
}
</script>
</head>
<body onLoad = "init()">
<canvas id="myCanvas" width="1000" height="1000"></canvas>
</body>
</html>
You need to put the z variable outside the loop, and save the position of each car in an object. You also need to check if position[i] is already defined to avoid incrementing the current position more times than needed.
var z;
var position;
function drawAll() {
clear();
for (var i = 0; i < cars.length; i++) {
temp = cars[i];
draw(temp);
if (temp.x + 100 < c.width) {
temp.x += temp.speed;
} else {
if (!position[i]) {
position[i] = z;
z++;
}
ctx.font = "20pt Verdana";
ctx.fillStyle = "#000";
ctx.fillText(position[i], 950, temp.y + 55);
}
}
requestAnimFrame(drawAll, c);
}
http://jsfiddle.net/acasaccia/u2vhaqyt/

Categories

Resources