Javascript tooltip positioning - javascript

I have integrated a tooltip on my website.
I am facing an issue as to the positioning from the top.
Below is the script that I have used.
var tooltip = function () {
var id = 'tt';
var top = 12;
var left = 3;
var maxw = 300;
var speed = 10;
var timer = 20;
var endalpha = 95;
var alpha = 0;
var tt, t, c, b, h;
var ie = document.all ? true : false;
return {
show: function (v, w) {
//debugger
if (tt == null) {
tt = document.createElement('div');
tt.setAttribute('id', id);
t = document.createElement('div');
t.setAttribute('id', id + 'top');
c = document.createElement('div');
c.setAttribute('id', id + 'cont');
b = document.createElement('div');
b.setAttribute('id', id + 'bot');
tt.appendChild(t);
tt.appendChild(c);
tt.appendChild(b);
document.body.appendChild(tt);
tt.style.opacity = 0;
tt.style.filter = 'alpha(opacity=0)';
document.onmousemove = this.pos;
}
tt.style.display = 'block';
var imagethemefolder;
if (window.theForm.ctl00$ddlSiteSkin) {
imagethemefolder = window.theForm.ctl00$ddlSiteSkin.value;
}
else {
imagethemefolder = window.parent.theForm.ctl00$ddlSiteSkin.value;
}
if (v == 'Save') {
v = '<img src="../Styles/Themes/' + imagethemefolder + '/Images/saveTooltip.png" class="ttImgPlacement" alt="" /><b class="ttTitle">Save</b><span class="ttContent">Select this option to Save the Records in database</span></strong>'
}
c.innerHTML = v;
//tt.style.width = w ? w + 'px' : 'auto';
if (!w && ie) {
t.style.display = 'none';
b.style.display = 'none';
//tt.style.width = tt.offsetWidth;
t.style.display = 'block';
b.style.display = 'block';
}
//if (tt.offsetWidth > maxw) {
tt.style.width = maxw + 'px'
//}
h = parseInt(tt.offsetHeight) + top;
clearInterval(tt.timer);
tt.timer = setInterval(function () { tooltip.fade(1) }, timer);
},
pos: function (e) {
//debugger
var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
if (ie) {
if ((event.screenY - event.offsetY) > 100) {
var ci = Math.ceil(event.screenY - event.offsetY);
if (GetRadWindow()) {
//var height = document.parentWindow.GetRadWindow().get_height()
ci = 60;
}
var restval = ci % 100;
restval = restval.roundTo(10) / 20;
if (restval >= 1) {
restval = restval - 1;
}
ci = ci.roundToLess(100);
tt.style.top = (ci + (20 * restval)) + 'px';
}
else {
tt.style.top = 50 + 'px';
}
}
else if (navigator.userAgent.indexOf('Firefox') != -1) {
//debugger
if ((e.screenY - e.layerY) > 100) {
var ci = Math.ceil(e.screenY - e.layerY);
if (GetRadWindow()) {
ci = 60;
}
var restval = ci % 100;
restval = restval.roundTo(10) / 20;
if (restval >= 1) {
restval = restval - 1;
}
ci = ci.roundToLess(100);
tt.style.top = (ci + (20 * restval)) + 'px';
}
else {
tt.style.top = 50 + 'px';
}
}
else {
if ((e.screenY) > 100) {
//debugger
var ci = Math.ceil(e.screenY);
if (GetRadWindow()) {
//debugger
ci = 80;
}
var restval = ci % 100;
restval = restval.roundTo(10) / 20;
if (restval >= 2) {
restval = restval - 2;
}
ci = ci.roundToLess(100);
tt.style.top = (ci + (20 * restval)) + 'px';
}
else {
tt.style.top = 50 + 'px';
}
}
//tt.style.top = ie ? (event.screenY - event.offsetY - top) + 'px' : (e.screenY - (e.layerY - top + 5)) + 'px';
if (l > (document.documentElement.offsetWidth - 305)) {
tt.style.left = (l + left - 300) + 'px';
}
else {
tt.style.left = (l + left) + 'px';
}
},
fade: function (d) {
var a = alpha;
if ((a != endalpha && d == 1) || (a != 0 && d == -1)) {
var i = speed;
if (endalpha - a < speed && d == 1) {
i = endalpha - a;
} else if (alpha < speed && d == -1) {
i = a;
}
alpha = a + (i * d);
tt.style.opacity = alpha * .01;
tt.style.filter = 'alpha(opacity=' + alpha + ')';
} else {
clearInterval(tt.timer);
if (d == -1) { tt.style.display = 'none' }
}
},
hide: function () {
clearInterval(tt.timer);
tt.timer = setInterval(function () { tooltip.fade(-1) }, timer);
}
};} ();
I have made lot of permutations and combinations to this and have made it work almost fine.
The only issue is that the top positioning is not displaying properly in browsers.
I am struck only for that part.

You can use the following script.
<script type="text/javascript">
$(document).ready(function() {
$('#id').qtip({
content: 'New Request Alt+N',
position: {
corner: {
target: 'topRight',
tooltip: 'bottomLeft'
}
},
show: 'mouseover',
hide: 'mouseout',
style: {
background: '#A2D959',
color: 'black',`enter code here`
textAlign: 'center',
border: {
radius: 4,
color: '#A2D959'
},
tip: 'bottomLeft'
}
});
});
</script>
for more details :
http://codersshop.blogspot.in/2013/06/tooltip-implementation-you-can-download.html

Related

How could I achieve the effect of "lava" leaving traces

After some time of "development" of the JavaScript game, I've came to a great idea, or so it seemed / sounded.
I was thinking of creating an entity which would represent lava. That lava would move in a specific direction, using:
function Lava(pos, ch) {
this.pos = pos;
this.size = new Vector(1, 1);
if(ch == '-') {
this.speed = new Vector(3, 0)
}
}
where is var acrotchar = {"-": Lava};.
The whole code can be seen here or below:
var LEVELS = [
[" x x",
" xx x",
" xxx x x",
" xx!xx x ox",
" x!!!x x xx",
" xx!xx x x",
" x xvx x x",
" x xx x",
" x x x",
" xx x x",
" x x xx",
" x x",
" x # xxxxx o x",
" xxxxxx xxxxxxxxx xxxxxxxxxxxxx",
" x x ",
" x!!!!!x ",
" x!!!!!x ",
" xxxxxxx ",
"--------------------------------------"]
];
//set variables (HP and EXP)
var life = 3;
var expo = 0;
document.getElementById("life").innerHTML = ("Lives left: " + life);
document.getElementById("expo").innerHTML = ("Points: " + expo);
//set the playzone
function Vector(x, y) {
this.x = x; this.y = y;
}
Vector.prototype.plus = function(other) {
return new Vector(this.x + other.x, this.y + other.y);
};
Vector.prototype.times = function(scale) {
return new Vector(this.x * scale, this.y * scale);
};
// Note: uppercase words are used that means constructor are values
var actorchars = {
"#": Player,
"o": Coin,
"=": Lava,
"|": Lava,
"v": Lava,
"#": Lava,
"-": Flood
};
function Player(pos) {
this.pos = pos.plus(new Vector(0, -.5));
this.size = new Vector(.5, 1);
this.speed = new Vector(0, 0);
}
Player.prototype.type = "player";
function Lava(pos, ch) {
this.pos = pos;
this.size = new Vector(1, 1);
if (ch === "=")
this.speed = new Vector(2, 0);
else if (ch === '|')
this.speed = new Vector(0, 2);
else if (ch === 'v'){
this.speed = new Vector(0, 5);
this.repeatPos = pos;
} else if (ch === '#')
this.speed = new Vector(0, 10);
}
Lava.prototype.type = "lava"
function Flood(pos, ch) {
this.pos = pos;
this.size = new Vector(1, 1);
if (ch === '-') {
this.speed = new Vector(0, 1);
this.repeatPos = pos; //will be removed in the future
}
}
Flood.prototype.type = "flood"
//Lava.prototype.type = "Lava";
// function Wall(pos, ch) {
// this.pos = pos;
// this.size = new Vector(1, 1);
// if (ch === "z")
// this.speed = new Vector(0, 1);
// }
// Wall.prototype.type = "wall"
function Coin(pos) {
this.basePos = this.pos = pos;
this.size = new Vector(.6, .6);
// take a look back
this.wobble = Math.random() * Math.PI * 2;
}
Coin.prototype.type = "coin";
Level.prototype.isFinished = function() {
return this.status !== null && this.finishDelay < 0;
};
function Level(plan) {
this.width = plan[0].length;
this.height = plan.length;
this.grid = [];
this.actors = [];
for (var y = 0; y < this.height; y++) {
var line = plan[y], gridLine = [];
for (var x = 0; x < this.width; x++) {
var ch = line[x], fieldType = null;
var Actor = actorchars[ch];
if (Actor)
this.actors.push(new Actor(new Vector(x, y), ch));
else if (ch === "x")
fieldType = "wall";
else if (ch === "z")
fieldType = "wall";
else if (ch === "!")
fieldType = "lava";
else if (ch === "|")
fieldType = "lava";
else if (ch === "=")
fieldType = "lava";
else if (ch === "#")
fieldType = "lava";
else if (ch === "-")
fieldType = "flood";
else if (ch === "v"){
fieldType = "lava";
console.log(fieldType);
}
gridLine.push(fieldType);
}
this.grid.push(gridLine);
}
this.player = this.actors.filter(function(actor) {
return actor.type === "player";
})[0];
this.status = this.finishDelay = null;
}
function element(name, className) {
var elem = document.createElement(name);
if(className) elem.className = className;
return elem;
}
function DOMDisplay(parent, level) {
this.wrap = parent.appendChild(element("div", "game"));
this.level = level;
this.wrap.appendChild(this.drawBackground());
this.actorLayer = null;
this.drawFrame();
}
var scale = 15;
DOMDisplay.prototype.drawBackground = function() {
var table = element("table", "background");
table.style.width = this.level.width * scale + "px";
table.style.height = this.level.height * scale + "px";
this.level.grid.forEach(function(row) {
var rowElement = table.appendChild(element("tr"));
rowElement.style.height = scale + "px";
row.forEach(function(type) {
rowElement.appendChild(element("td", type));
});
});
return table;
};
DOMDisplay.prototype.drawActors = function() {
var wrap = element("div");
this.level.actors.forEach(function(actor) {
var rect = wrap.appendChild(element("div", "actor " + actor.type));
rect.style.width = actor.size.x * scale + "px";
rect.style.height = actor.size.y * scale + "px";
rect.style.left = actor.pos.x * scale + "px";
rect.style.top = actor.pos.y * scale + "px";
});
return wrap;
};
DOMDisplay.prototype.drawFrame = function() {
if (this.actorLayer)
this.wrap.removeChild(this.actorLayer);
this.actorLayer = this.wrap.appendChild(this.drawActors());
this.wrap.className = "game " + (this.level.status || "");
this.scrollPlayerIntoView();
};
// clear it later
DOMDisplay.prototype.scrollPlayerIntoView = function() {
var width = this.wrap.clientWidth;
var height = this.wrap.clientHeight;
var margin = width / 3;
// The viewport
var left = this.wrap.scrollLeft, right = left + width;
var top = this.wrap.scrollTop, bottom = top + height;
var player = this.level.player;
var center = player.pos.plus(player.size.times(0.5))
.times(scale);
if (center.x < left + margin)
this.wrap.scrollLeft = center.x - margin;
else if (center.x > right - margin)
this.wrap.scrollLeft = center.x + margin - width;
if (center.y < top + margin)
this.wrap.scrollTop = center.y - margin;
else if (center.y > bottom - margin)
this.wrap.scrollTop = center.y + margin - height;
};
DOMDisplay.prototype.clear = function() {
this.wrap.parentNode.removeChild(this.wrap);
};
Level.prototype.obstacleAt = function(pos, size) {
var xStart = Math.floor(pos.x);
var xEnd = Math.ceil(pos.x + size.x);
var yStart = Math.floor(pos.y);
var yEnd = Math.ceil(pos.y + size.y);
if (xStart < 0 || xEnd > this.width || yStart < 0)
return "wall";
if (yEnd > this.height)
return "lava", "flood";
for (var y = yStart; y < yEnd; y++) {
for (var x = xStart; x < xEnd; x++) {
var fieldType = this.grid[y][x];
if (fieldType) return fieldType;
}
}
};
Level.prototype.actorAt = function(actor) {
for (var i = 0; i < this.actors.length; i++) {
var other = this.actors[i];
if (other != actor &&
actor.pos.x + actor.size.x > other.pos.x &&
actor.pos.x < other.pos.x + other.size.x &&
actor.pos.y + actor.size.y > other.pos.y &&
actor.pos.y < other.pos.y + other.size.y)
return other;
}
};
var maxStep = 0.05;
Level.prototype.animate = function(step, keys) {
if (this.status !== null)
this.finishDelay -= step;
while (step > 0) {
var thisStep = Math.min(step, maxStep);
this.actors.forEach(function(actor) {
actor.act(thisStep, this, keys);
}, this);
step -= thisStep;
}
};
Lava.prototype.act = function(step, level) {
var newPos = this.pos.plus(this.speed.times(step));
if (!level.obstacleAt(newPos, this.size))
this.pos = newPos;
else if (this.repeatPos)
this.pos = this.repeatPos;
else
this.speed = this.speed.times(-1);
};
Flood.prototype.act = function(step, level) {
var newPos = this.pos.plus(this.speed.times(step));
if (!level.obstacleAt(newPos, this.size))
this.pos = newPos;
else
this.speed = this.speed.times(-1);
};
var wobbleSpeed = 8, wobbleDist = 0.07;
Coin.prototype.act = function(step) {
this.wobble += step * wobbleSpeed;
var wobblePos = Math.sin(this.wobble) * wobbleDist;
this.pos = this.basePos.plus(new Vector(0, wobblePos));
};
var playerXSpeed = 10;
Player.prototype.moveX = function(step, level, keys) {
this.speed.x = 0;
if (keys.left) this.speed.x -= playerXSpeed;
if (keys.right) this.speed.x += playerXSpeed;
var motion = new Vector(this.speed.x * step, 0);
var newPos = this.pos.plus(motion);
var obstacle = level.obstacleAt(newPos, this.size);
if (obstacle)
level.playerTouched(obstacle);
else
this.pos = newPos;
};
var gravity = 30;
var jumpSpeed = 17;
Player.prototype.moveY = function(step, level, keys) {
this.speed.y += step * gravity;
var motion = new Vector(0, this.speed.y * step);
var newPos = this.pos.plus(motion);
var obstacle = level.obstacleAt(newPos, this.size);
if (obstacle) {
level.playerTouched(obstacle);
if (keys.up && this.speed.y > 0)
this.speed.y = -jumpSpeed;
else
this.speed.y = 0;
} else {
this.pos = newPos;
}
};
Player.prototype.act = function(step, level, keys) {
this.moveX(step, level, keys);
this.moveY(step, level, keys);
var otherActor = level.actorAt(this);
if (otherActor)
level.playerTouched(otherActor.type, otherActor);
// Losing animation
if (level.status == "lost") {
this.pos.y += step;
this.size.y -= step;
}
};
Level.prototype.playerTouched = function(type, actor) {
//if (type == "lava" || type == "Lava" && this.status === null) { //DOESN'T SEEM TO WORK, FIND OUT WHY MASS DAMAGE
if (type == "lava" && this.status === null || type == "flood" && this.status === null) {
this.status = "lost";
life -= 1;
console.log(life);
expo = 0;
document.getElementById("expo").innerHTML = ("Points: " + expo);
document.getElementById("life").innerHTML = ("Lives left: " + life);
if(life < 0) {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}
this.finishDelay = 1;
} else if (type == "coin") {
expo += 1;
document.getElementById("expo").innerHTML = ("Points: " + expo);
this.actors = this.actors.filter(function(other) {
return other != actor;
});
if (!this.actors.some(function(actor) {
return actor.type == "coin";
})) {
life += 1;
document.getElementById("life").innerHTML = ("Lives left: " + life);
this.status = "won";
this.finishDelay = 1;
}
}
};
var arrowCodes = {37: "left", 38: "up", 39: "right"};
function trackKeys(codes) {
var pressed = Object.create(null);
function handler(event) {
if (codes.hasOwnProperty(event.keyCode)) {
var down = event.type == "keydown";
pressed[codes[event.keyCode]] = down;
event.preventDefault();
}
}
addEventListener("keydown", handler);
addEventListener("keyup", handler);
return pressed;
}
function runAnimation(frameFunc) {
var lastTime = null;
function frame(time) {
var stop = false;
if (lastTime !== null) {
var timeStep = Math.min(time - lastTime, 100) / 1000;
stop = frameFunc(timeStep) === false;
}
lastTime = time;
if (!stop)
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
var arrows = trackKeys(arrowCodes);
function runLevel(level, Display, andThen) {
var display = new Display(document.body, level);
runAnimation(function(step) {
level.animate(step, arrows);
display.drawFrame(step);
if (level.isFinished()) {
display.clear();
if (andThen)
andThen(level.status);
return false;
}
});
}
var lives = function() {
ctx.font = "20px Courier";
ctx.fontFamily = "monospace";
ctx.fillStyle = "#666";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Lives left: " + life, 10, 10);
};
function runGame(plans, Display) {
function startLevel(n) {
runLevel(new Level(plans[n]), Display, function(status) {
if (status == "lost") {
startLevel(n);
} else if (n < plans.length - 1)
startLevel(n + 1);
else
alert("You win!");
});
}
startLevel(0);
}
runGame(LEVELS, DOMDisplay);
body {
background: #222;
}
h2 {
color: #666;
font-family: monospace;
text-align: center;
}
.background {
table-layout: fixed;
border-spacing: 0;
}
.background td {
padding: 0;
}
.lava, .actor {
background: #e55;
}
.wall {
background: #444;
border: solid 3px #333;
box-sizing: content-box;
}
.actor {
position: absolute;
}
.coin {
background: #e2e838;
border-radius: 50%;
}
.player {
background: #335699;
box-shadow: none;
}
.lost .player {
background: #a04040;
}
.won .player {
background: green;
}
.game {
position: relative;
overflow: hidden;
}
#life, #expo {
font-size: 16px;
font-family: monospace;
color: #666;
text-align: left;
baseline: top;
margin-left: 30px;
font-weight: bold;
}
input {
margin-left: 30px;
}
<h2>Simple JavaScript Game</h2>
<div id="life"></div>
<div id="expo"></div>
What I would like to achieve is the following:
Lava (red colored blocks, in code presented as "-", tagged as "flood") that would:
move in a specific direction (is already done, more or less),
leaves "trace" behind it's movement, (technically speaking, the lava level in this case would seem as it is rising up),
"flood" is able to go through the objects (optional, as I have to check the whole code carefully on my own to see where did I give the entity the "collisions")
I would really appreciate any help, especially with the lava rising effect.
Everything did not fit in one post, so here is the rest:
To make the lava rise through the objects, just reverse the speed and remove the obstacleAt if statement. To make the lava appear like it is behind objects, just add a css class lava-flood and set the z-index to something like -1. If you want the lava to rise in front of the objects, just remove the z-index property from the lava-flood class in CSS.
Full code - lava rising behind objects
var LEVELS = [
[" x x",
" xx x",
" xxx x x",
" xx!xx x ox",
" x!!!x x xx",
" xx!xx x x",
" x xvx x x",
" x xx x",
" x x x",
" xx x x",
" x x xx",
" x x",
" x # xxxxx o x",
" xxxxxx xxxxxxxxx xxxxxxxxxxxxx",
" x x ",
" x!!!!!x ",
" x!!!!!x ",
" xxxxxxx ",
"--------------------------------------"]
];
//set variables (HP and EXP)
var life = 3;
var expo = 0;
document.getElementById("life").innerHTML = ("Lives left: " + life);
document.getElementById("expo").innerHTML = ("Points: " + expo);
//set the playzone
function Vector(x, y) {
this.x = x; this.y = y;
}
Vector.prototype.plus = function(other) {
return new Vector(this.x + other.x, this.y + other.y);
};
Vector.prototype.times = function(scale) {
return new Vector(this.x * scale, this.y * scale);
};
// Note: uppercase words are used that means constructor are values
var actorchars = {
"#": Player,
"o": Coin,
"=": Lava,
"|": Lava,
"v": Lava,
"#": Lava,
"-": LavaFlood
};
function Player(pos) {
this.pos = pos.plus(new Vector(0, -.5));
this.size = new Vector(.5, 1);
this.speed = new Vector(0, 0);
}
Player.prototype.type = "player";
function Lava(pos, ch) {
this.pos = pos;
this.size = new Vector(1, 1);
if (ch === "=")
this.speed = new Vector(2, 0);
else if (ch === '|')
this.speed = new Vector(0, 2);
else if (ch === 'v'){
this.speed = new Vector(0, 5);
this.repeatPos = pos;
} else if (ch === '#')
this.speed = new Vector(0, 10);
}
Lava.prototype.type = "lava"
function LavaFlood(pos, ch) {
this.pos = pos;
this.size = new Vector(1, 1);
this.trueSize = new Vector(1, 1);
if (ch === '-') {
this.speed = new Vector(0, -1);
this.repeatPos = pos; //will be removed in the future
}
}
LavaFlood.prototype.type = "lava-flood"
//Lava.prototype.type = "Lava";
// function Wall(pos, ch) {
// this.pos = pos;
// this.size = new Vector(1, 1);
// if (ch === "z")
// this.speed = new Vector(0, 1);
// }
// Wall.prototype.type = "wall"
function Coin(pos) {
this.basePos = this.pos = pos;
this.size = new Vector(.6, .6);
// take a look back
this.wobble = Math.random() * Math.PI * 2;
}
Coin.prototype.type = "coin";
Level.prototype.isFinished = function() {
return this.status !== null && this.finishDelay < 0;
};
function Level(plan) {
this.width = plan[0].length;
this.height = plan.length;
this.grid = [];
this.actors = [];
for (var y = 0; y < this.height; y++) {
var line = plan[y], gridLine = [];
for (var x = 0; x < this.width; x++) {
var ch = line[x], fieldType = null;
var Actor = actorchars[ch];
if (Actor)
this.actors.push(new Actor(new Vector(x, y), ch));
else if (ch === "x")
fieldType = "wall";
else if (ch === "z")
fieldType = "wall";
else if (ch === "!")
fieldType = "lava";
else if (ch === "|")
fieldType = "lava";
else if (ch === "=")
fieldType = "lava";
else if (ch === "#")
fieldType = "lava";
else if (ch === "-")
fieldType = "lava-flood";
else if (ch === "v"){
fieldType = "lava";
console.log(fieldType);
}
gridLine.push(fieldType);
}
this.grid.push(gridLine);
}
this.player = this.actors.filter(function(actor) {
return actor.type === "player";
})[0];
this.status = this.finishDelay = null;
}
function element(name, className) {
var elem = document.createElement(name);
if(className) elem.className = className;
return elem;
}
function DOMDisplay(parent, level) {
this.wrap = parent.appendChild(element("div", "game"));
this.level = level;
this.wrap.appendChild(this.drawBackground());
this.actorLayer = null;
this.drawFrame();
}
var scale = 15;
DOMDisplay.prototype.drawBackground = function() {
var table = element("table", "background");
table.style.width = this.level.width * scale + "px";
table.style.height = this.level.height * scale + "px";
this.level.grid.forEach(function(row) {
var rowElement = table.appendChild(element("tr"));
rowElement.style.height = scale + "px";
row.forEach(function(type) {
rowElement.appendChild(element("td", type));
});
});
return table;
};
DOMDisplay.prototype.drawActors = function() {
var wrap = element("div");
this.level.actors.forEach(function(actor) {
var rect = wrap.appendChild(element("div", "actor " + actor.type));
rect.style.width = actor.size.x * scale + "px";
rect.style.height = actor.size.y * scale + "px";
rect.style.left = actor.pos.x * scale + "px";
rect.style.top = actor.pos.y * scale + "px";
});
return wrap;
};
DOMDisplay.prototype.drawFrame = function() {
if (this.actorLayer)
this.wrap.removeChild(this.actorLayer);
this.actorLayer = this.wrap.appendChild(this.drawActors());
this.wrap.className = "game " + (this.level.status || "");
this.scrollPlayerIntoView();
};
// clear it later
DOMDisplay.prototype.scrollPlayerIntoView = function() {
var width = this.wrap.clientWidth;
var height = this.wrap.clientHeight;
var margin = width / 3;
// The viewport
var left = this.wrap.scrollLeft, right = left + width;
var top = this.wrap.scrollTop, bottom = top + height;
var player = this.level.player;
var center = player.pos.plus(player.size.times(0.5))
.times(scale);
if (center.x < left + margin)
this.wrap.scrollLeft = center.x - margin;
else if (center.x > right - margin)
this.wrap.scrollLeft = center.x + margin - width;
if (center.y < top + margin)
this.wrap.scrollTop = center.y - margin;
else if (center.y > bottom - margin)
this.wrap.scrollTop = center.y + margin - height;
};
DOMDisplay.prototype.clear = function() {
this.wrap.parentNode.removeChild(this.wrap);
};
Level.prototype.obstacleAt = function(pos, size) {
var xStart = Math.floor(pos.x);
var xEnd = Math.ceil(pos.x + size.x);
var yStart = Math.floor(pos.y);
var yEnd = Math.ceil(pos.y + size.y);
if (xStart < 0 || xEnd > this.width || yStart < 0)
return "wall";
if (yEnd > this.height)
return "lava", "lava-flood";
for (var y = yStart; y < yEnd; y++) {
for (var x = xStart; x < xEnd; x++) {
var fieldType = this.grid[y][x];
if (fieldType) return fieldType;
}
}
};
Level.prototype.actorAt = function(actor) {
for (var i = 0; i < this.actors.length; i++) {
var other = this.actors[i];
if (other != actor &&
actor.pos.x + actor.size.x > other.pos.x &&
actor.pos.x < other.pos.x + other.size.x &&
actor.pos.y + actor.size.y > other.pos.y &&
actor.pos.y < other.pos.y + other.size.y)
return other;
}
};
var maxStep = 0.05;
Level.prototype.animate = function(step, keys) {
if (this.status !== null)
this.finishDelay -= step;
while (step > 0) {
var thisStep = Math.min(step, maxStep);
this.actors.forEach(function(actor) {
actor.act(thisStep, this, keys);
}, this);
step -= thisStep;
}
};
Lava.prototype.act = function(step, level) {
var newPos = this.pos.plus(this.speed.times(step));
if (!level.obstacleAt(newPos, this.size))
this.pos = newPos;
else if (this.repeatPos)
this.pos = this.repeatPos;
else
this.speed = this.speed.times(-1);
};
LavaFlood.prototype.act = function(step, level) {
this.pos = this.pos.plus(this.speed.times(step));
this.size = this.size.plus(this.speed.times(-step));
};
var wobbleSpeed = 8, wobbleDist = 0.07;
Coin.prototype.act = function(step) {
this.wobble += step * wobbleSpeed;
var wobblePos = Math.sin(this.wobble) * wobbleDist;
this.pos = this.basePos.plus(new Vector(0, wobblePos));
};
var playerXSpeed = 10;
Player.prototype.moveX = function(step, level, keys) {
this.speed.x = 0;
if (keys.left) this.speed.x -= playerXSpeed;
if (keys.right) this.speed.x += playerXSpeed;
var motion = new Vector(this.speed.x * step, 0);
var newPos = this.pos.plus(motion);
var obstacle = level.obstacleAt(newPos, this.size);
if (obstacle)
level.playerTouched(obstacle);
else
this.pos = newPos;
};
var gravity = 30;
var jumpSpeed = 17;
Player.prototype.moveY = function(step, level, keys) {
this.speed.y += step * gravity;
var motion = new Vector(0, this.speed.y * step);
var newPos = this.pos.plus(motion);
var obstacle = level.obstacleAt(newPos, this.size);
if (obstacle) {
level.playerTouched(obstacle);
if (keys.up && this.speed.y > 0)
this.speed.y = -jumpSpeed;
else
this.speed.y = 0;
} else {
this.pos = newPos;
}
};
Player.prototype.act = function(step, level, keys) {
this.moveX(step, level, keys);
this.moveY(step, level, keys);
var otherActor = level.actorAt(this);
if (otherActor)
level.playerTouched(otherActor.type, otherActor);
// Losing animation
if (level.status == "lost") {
this.pos.y += step;
this.size.y -= step;
}
};
Level.prototype.playerTouched = function(type, actor) {
//if (type == "lava" || type == "Lava" && this.status === null) { //DOESN'T SEEM TO WORK, FIND OUT WHY MASS DAMAGE
if (type == "lava" && this.status === null || type == "lava-flood" && this.status === null) {
this.status = "lost";
life -= 1;
console.log(life);
expo = 0;
document.getElementById("expo").innerHTML = ("Points: " + expo);
document.getElementById("life").innerHTML = ("Lives left: " + life);
if(life < 0) {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}
this.finishDelay = 1;
} else if (type == "coin") {
expo += 1;
document.getElementById("expo").innerHTML = ("Points: " + expo);
this.actors = this.actors.filter(function(other) {
return other != actor;
});
if (!this.actors.some(function(actor) {
return actor.type == "coin";
})) {
life += 1;
document.getElementById("life").innerHTML = ("Lives left: " + life);
this.status = "won";
this.finishDelay = 1;
}
}
};
var arrowCodes = {37: "left", 38: "up", 39: "right"};
function trackKeys(codes) {
var pressed = Object.create(null);
function handler(event) {
if (codes.hasOwnProperty(event.keyCode)) {
var down = event.type == "keydown";
pressed[codes[event.keyCode]] = down;
event.preventDefault();
}
}
addEventListener("keydown", handler);
addEventListener("keyup", handler);
return pressed;
}
function runAnimation(frameFunc) {
var lastTime = null;
function frame(time) {
var stop = false;
if (lastTime !== null) {
var timeStep = Math.min(time - lastTime, 100) / 1000;
stop = frameFunc(timeStep) === false;
}
lastTime = time;
if (!stop)
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
var arrows = trackKeys(arrowCodes);
function runLevel(level, Display, andThen) {
var display = new Display(document.body, level);
runAnimation(function(step) {
level.animate(step, arrows);
display.drawFrame(step);
if (level.isFinished()) {
display.clear();
if (andThen)
andThen(level.status);
return false;
}
});
}
var lives = function() {
ctx.font = "20px Courier";
ctx.fontFamily = "monospace";
ctx.fillStyle = "#666";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Lives left: " + life, 10, 10);
};
function runGame(plans, Display) {
function startLevel(n) {
runLevel(new Level(plans[n]), Display, function(status) {
if (status == "lost") {
startLevel(n);
} else if (n < plans.length - 1)
startLevel(n + 1);
else
alert("You win!");
});
}
startLevel(0);
}
runGame(LEVELS, DOMDisplay);
body {
background: #222;
}
h2 {
color: #666;
font-family: monospace;
text-align: center;
}
.background {
table-layout: fixed;
border-spacing: 0;
}
.background td {
padding: 0;
}
.lava, .actor {
background: #e55;
}
.lava-flood {
z-index: -1;
}
.wall {
background: #444;
border: solid 3px #333;
box-sizing: content-box;
}
.actor {
position: absolute;
}
.coin {
background: #e2e838;
border-radius: 50%;
}
.player {
background: #335699;
box-shadow: none;
}
.lost .player {
background: #a04040;
}
.won .player {
background: green;
}
.game {
position: relative;
overflow: hidden;
}
#life, #expo {
font-size: 16px;
font-family: monospace;
color: #666;
text-align: left;
baseline: top;
margin-left: 30px;
font-weight: bold;
}
input {
margin-left: 30px;
}
<h2>Simple JavaScript Game</h2>
<div id="life"></div>
<div id="expo"></div>
If you need clarification or help for anything, please feel free to ask.
Your game is quite well made, but I have a few suggestions:
Please, please don't use prototypes to add functions to Objects. It makes is very difficult for someone not familiar with the code to follow. A better way is to put all the member functions in the same object, so they are grouped together. It makes the code (in my opinion) way easier to read and understand.
For example:
function Flood(pos, ch){
this.pos = pos;
//other assignments
this.act = function(){
//code
}
//other functions
}
Keeping all your functions in one class also makes it easier to find a function rather than hunting through the whole file to find it.
Even though most of the game is already written, it might be worthwhile looking into the new ES6 class syntax, because this is the perfect example for inheritance and object oriented programming. You can have a generic GridElement class that implements the all standard behaviours, and extend and modify only the parts that differ from type to type. This approach is extremely powerful, and makes it very easy to add new types. I would highly recommend reading more on the theory of object oriented programming, because it is a very useful tool, especially in large projects. Daniel Shiffman is an awesome YouTuber, and makes amazing videos about programming. He has an entire series on Object Oriented programming on youtube, and I would suggest watching the video here.
Don't display the elements in the main display function. Instead, let each class have it's own display function that returns a div element. You can call each element's display function in the main display loop. That way, it becomes much easier to add additional behaviour to particular classes. If the Flood object had its own display function, then it could return a noncontinuous trail instead of modifying its size, which is not the ideal way to implement this behaviour.
I am unaware of any place on earth where there are floods of Lava, and so I would suggest that you use more accurate names in your code. When I see Flood, I immediately think of water, and it led to a bit of head scratching for me to figure out that Flood was in fact, rising lava. A better class name could have been LavaFlood, so I have taken the liberty of changing the name of the class Flood to LavaFlood in the code below.
As for the lava rising effect, it was quite simple. All I did was add a trueSize variable to the (Lava)Flood class and change the act function:
(I could not post this as normal code, as the site kept saying that the code was not formatted properly)
LavaFlood.prototype.act = function(step, level) {
var newPos = this.pos.plus(this.speed.times(step));
if (!level.obstacleAt(newPos, this.trueSize)) {
this.size = this.size.plus(this.speed.times(-step));
this.pos = newPos;
} else
this.speed = this.speed.times(-1);
};
Full code - lava rising:
var LEVELS = [
[" x x",
" xx x",
" xxx x x",
" xx!xx x ox",
" x!!!x x xx",
" xx!xx x x",
" x xvx x x",
" x xx x",
" x x x",
" xx x x",
" x x xx",
" x x",
" x # xxxxx o x",
" xxxxxx xxxxxxxxx xxxxxxxxxxxxx",
" x x ",
" x!!!!!x ",
" x!!!!!x ",
" xxxxxxx ",
"--------------------------------------"]
];
//set variables (HP and EXP)
var life = 3;
var expo = 0;
document.getElementById("life").innerHTML = ("Lives left: " + life);
document.getElementById("expo").innerHTML = ("Points: " + expo);
//set the playzone
function Vector(x, y) {
this.x = x; this.y = y;
}
Vector.prototype.plus = function(other) {
return new Vector(this.x + other.x, this.y + other.y);
};
Vector.prototype.times = function(scale) {
return new Vector(this.x * scale, this.y * scale);
};
// Note: uppercase words are used that means constructor are values
var actorchars = {
"#": Player,
"o": Coin,
"=": Lava,
"|": Lava,
"v": Lava,
"#": Lava,
"-": LavaFlood
};
function Player(pos) {
this.pos = pos.plus(new Vector(0, -.5));
this.size = new Vector(.5, 1);
this.speed = new Vector(0, 0);
}
Player.prototype.type = "player";
function Lava(pos, ch) {
this.pos = pos;
this.size = new Vector(1, 1);
if (ch === "=")
this.speed = new Vector(2, 0);
else if (ch === '|')
this.speed = new Vector(0, 2);
else if (ch === 'v'){
this.speed = new Vector(0, 5);
this.repeatPos = pos;
} else if (ch === '#')
this.speed = new Vector(0, 10);
}
Lava.prototype.type = "lava"
function LavaFlood(pos, ch) {
this.pos = pos;
this.size = new Vector(1, 1);
this.trueSize = new Vector(1, 1);
if (ch === '-') {
this.speed = new Vector(0, -1);
this.repeatPos = pos; //will be removed in the future
}
}
LavaFlood.prototype.type = "lava-flood"
//Lava.prototype.type = "Lava";
// function Wall(pos, ch) {
// this.pos = pos;
// this.size = new Vector(1, 1);
// if (ch === "z")
// this.speed = new Vector(0, 1);
// }
// Wall.prototype.type = "wall"
function Coin(pos) {
this.basePos = this.pos = pos;
this.size = new Vector(.6, .6);
// take a look back
this.wobble = Math.random() * Math.PI * 2;
}
Coin.prototype.type = "coin";
Level.prototype.isFinished = function() {
return this.status !== null && this.finishDelay < 0;
};
function Level(plan) {
this.width = plan[0].length;
this.height = plan.length;
this.grid = [];
this.actors = [];
for (var y = 0; y < this.height; y++) {
var line = plan[y], gridLine = [];
for (var x = 0; x < this.width; x++) {
var ch = line[x], fieldType = null;
var Actor = actorchars[ch];
if (Actor)
this.actors.push(new Actor(new Vector(x, y), ch));
else if (ch === "x")
fieldType = "wall";
else if (ch === "z")
fieldType = "wall";
else if (ch === "!")
fieldType = "lava";
else if (ch === "|")
fieldType = "lava";
else if (ch === "=")
fieldType = "lava";
else if (ch === "#")
fieldType = "lava";
else if (ch === "-")
fieldType = "lava-flood";
else if (ch === "v"){
fieldType = "lava";
console.log(fieldType);
}
gridLine.push(fieldType);
}
this.grid.push(gridLine);
}
this.player = this.actors.filter(function(actor) {
return actor.type === "player";
})[0];
this.status = this.finishDelay = null;
}
function element(name, className) {
var elem = document.createElement(name);
if(className) elem.className = className;
return elem;
}
function DOMDisplay(parent, level) {
this.wrap = parent.appendChild(element("div", "game"));
this.level = level;
this.wrap.appendChild(this.drawBackground());
this.actorLayer = null;
this.drawFrame();
}
var scale = 15;
DOMDisplay.prototype.drawBackground = function() {
var table = element("table", "background");
table.style.width = this.level.width * scale + "px";
table.style.height = this.level.height * scale + "px";
this.level.grid.forEach(function(row) {
var rowElement = table.appendChild(element("tr"));
rowElement.style.height = scale + "px";
row.forEach(function(type) {
rowElement.appendChild(element("td", type));
});
});
return table;
};
DOMDisplay.prototype.drawActors = function() {
var wrap = element("div");
this.level.actors.forEach(function(actor) {
var rect = wrap.appendChild(element("div", "actor " + actor.type));
rect.style.width = actor.size.x * scale + "px";
rect.style.height = actor.size.y * scale + "px";
rect.style.left = actor.pos.x * scale + "px";
rect.style.top = actor.pos.y * scale + "px";
});
return wrap;
};
DOMDisplay.prototype.drawFrame = function() {
if (this.actorLayer)
this.wrap.removeChild(this.actorLayer);
this.actorLayer = this.wrap.appendChild(this.drawActors());
this.wrap.className = "game " + (this.level.status || "");
this.scrollPlayerIntoView();
};
// clear it later
DOMDisplay.prototype.scrollPlayerIntoView = function() {
var width = this.wrap.clientWidth;
var height = this.wrap.clientHeight;
var margin = width / 3;
// The viewport
var left = this.wrap.scrollLeft, right = left + width;
var top = this.wrap.scrollTop, bottom = top + height;
var player = this.level.player;
var center = player.pos.plus(player.size.times(0.5))
.times(scale);
if (center.x < left + margin)
this.wrap.scrollLeft = center.x - margin;
else if (center.x > right - margin)
this.wrap.scrollLeft = center.x + margin - width;
if (center.y < top + margin)
this.wrap.scrollTop = center.y - margin;
else if (center.y > bottom - margin)
this.wrap.scrollTop = center.y + margin - height;
};
DOMDisplay.prototype.clear = function() {
this.wrap.parentNode.removeChild(this.wrap);
};
Level.prototype.obstacleAt = function(pos, size) {
var xStart = Math.floor(pos.x);
var xEnd = Math.ceil(pos.x + size.x);
var yStart = Math.floor(pos.y);
var yEnd = Math.ceil(pos.y + size.y);
if (xStart < 0 || xEnd > this.width || yStart < 0)
return "wall";
if (yEnd > this.height)
return "lava", "lava-flood";
for (var y = yStart; y < yEnd; y++) {
for (var x = xStart; x < xEnd; x++) {
var fieldType = this.grid[y][x];
if (fieldType) return fieldType;
}
}
};
Level.prototype.actorAt = function(actor) {
for (var i = 0; i < this.actors.length; i++) {
var other = this.actors[i];
if (other != actor &&
actor.pos.x + actor.size.x > other.pos.x &&
actor.pos.x < other.pos.x + other.size.x &&
actor.pos.y + actor.size.y > other.pos.y &&
actor.pos.y < other.pos.y + other.size.y)
return other;
}
};
var maxStep = 0.05;
Level.prototype.animate = function(step, keys) {
if (this.status !== null)
this.finishDelay -= step;
while (step > 0) {
var thisStep = Math.min(step, maxStep);
this.actors.forEach(function(actor) {
actor.act(thisStep, this, keys);
}, this);
step -= thisStep;
}
};
Lava.prototype.act = function(step, level) {
var newPos = this.pos.plus(this.speed.times(step));
if (!level.obstacleAt(newPos, this.size))
this.pos = newPos;
else if (this.repeatPos)
this.pos = this.repeatPos;
else
this.speed = this.speed.times(-1);
};
LavaFlood.prototype.act = function(step, level) {
var newPos = this.pos.plus(this.speed.times(step));
if (!level.obstacleAt(newPos, this.trueSize)){
this.size = this.size.plus(this.speed.times(-step));
this.pos = newPos;
}
else
this.speed = this.speed.times(-1);
};
var wobbleSpeed = 8, wobbleDist = 0.07;
Coin.prototype.act = function(step) {
this.wobble += step * wobbleSpeed;
var wobblePos = Math.sin(this.wobble) * wobbleDist;
this.pos = this.basePos.plus(new Vector(0, wobblePos));
};
var playerXSpeed = 10;
Player.prototype.moveX = function(step, level, keys) {
this.speed.x = 0;
if (keys.left) this.speed.x -= playerXSpeed;
if (keys.right) this.speed.x += playerXSpeed;
var motion = new Vector(this.speed.x * step, 0);
var newPos = this.pos.plus(motion);
var obstacle = level.obstacleAt(newPos, this.size);
if (obstacle)
level.playerTouched(obstacle);
else
this.pos = newPos;
};
var gravity = 30;
var jumpSpeed = 17;
Player.prototype.moveY = function(step, level, keys) {
this.speed.y += step * gravity;
var motion = new Vector(0, this.speed.y * step);
var newPos = this.pos.plus(motion);
var obstacle = level.obstacleAt(newPos, this.size);
if (obstacle) {
level.playerTouched(obstacle);
if (keys.up && this.speed.y > 0)
this.speed.y = -jumpSpeed;
else
this.speed.y = 0;
} else {
this.pos = newPos;
}
};
Player.prototype.act = function(step, level, keys) {
this.moveX(step, level, keys);
this.moveY(step, level, keys);
var otherActor = level.actorAt(this);
if (otherActor)
level.playerTouched(otherActor.type, otherActor);
// Losing animation
if (level.status == "lost") {
this.pos.y += step;
this.size.y -= step;
}
};
Level.prototype.playerTouched = function(type, actor) {
//if (type == "lava" || type == "Lava" && this.status === null) { //DOESN'T SEEM TO WORK, FIND OUT WHY MASS DAMAGE
if (type == "lava" && this.status === null || type == "lava-flood" && this.status === null) {
this.status = "lost";
life -= 1;
console.log(life);
expo = 0;
document.getElementById("expo").innerHTML = ("Points: " + expo);
document.getElementById("life").innerHTML = ("Lives left: " + life);
if(life < 0) {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}
this.finishDelay = 1;
} else if (type == "coin") {
expo += 1;
document.getElementById("expo").innerHTML = ("Points: " + expo);
this.actors = this.actors.filter(function(other) {
return other != actor;
});
if (!this.actors.some(function(actor) {
return actor.type == "coin";
})) {
life += 1;
document.getElementById("life").innerHTML = ("Lives left: " + life);
this.status = "won";
this.finishDelay = 1;
}
}
};
var arrowCodes = {37: "left", 38: "up", 39: "right"};
function trackKeys(codes) {
var pressed = Object.create(null);
function handler(event) {
if (codes.hasOwnProperty(event.keyCode)) {
var down = event.type == "keydown";
pressed[codes[event.keyCode]] = down;
event.preventDefault();
}
}
addEventListener("keydown", handler);
addEventListener("keyup", handler);
return pressed;
}
function runAnimation(frameFunc) {
var lastTime = null;
function frame(time) {
var stop = false;
if (lastTime !== null) {
var timeStep = Math.min(time - lastTime, 100) / 1000;
stop = frameFunc(timeStep) === false;
}
lastTime = time;
if (!stop)
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
var arrows = trackKeys(arrowCodes);
function runLevel(level, Display, andThen) {
var display = new Display(document.body, level);
runAnimation(function(step) {
level.animate(step, arrows);
display.drawFrame(step);
if (level.isFinished()) {
display.clear();
if (andThen)
andThen(level.status);
return false;
}
});
}
var lives = function() {
ctx.font = "20px Courier";
ctx.fontFamily = "monospace";
ctx.fillStyle = "#666";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Lives left: " + life, 10, 10);
};
function runGame(plans, Display) {
function startLevel(n) {
runLevel(new Level(plans[n]), Display, function(status) {
if (status == "lost") {
startLevel(n);
} else if (n < plans.length - 1)
startLevel(n + 1);
else
alert("You win!");
});
}
startLevel(0);
}
runGame(LEVELS, DOMDisplay);
body {
background: #222;
}
h2 {
color: #666;
font-family: monospace;
text-align: center;
}
.background {
table-layout: fixed;
border-spacing: 0;
}
.background td {
padding: 0;
}
.lava, .actor {
background: #e55;
}
.wall {
background: #444;
border: solid 3px #333;
box-sizing: content-box;
}
.actor {
position: absolute;
}
.coin {
background: #e2e838;
border-radius: 50%;
}
.player {
background: #335699;
box-shadow: none;
}
.lost .player {
background: #a04040;
}
.won .player {
background: green;
}
.game {
position: relative;
overflow: hidden;
}
#life, #expo {
font-size: 16px;
font-family: monospace;
color: #666;
text-align: left;
baseline: top;
margin-left: 30px;
font-weight: bold;
}
input {
margin-left: 30px;
}
<h2>Simple JavaScript Game</h2>
<div id="life"></div>
<div id="expo"></div>
If you need clarification or help for anything, please feel free to ask.

Can't read property 'addEventListener' of null

I am working on a college project that requires me to build a 2D game in javascript. A problem that I'm having at the moment is that it cannot read the 'addEventListener'. This error has caused my game to not work completely.
document.getElementById('restart').addEventListener('click', startGame);
Here is the full code that I have used. The error is down the very bottom.
(function()
{
//Define variables
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var player, score, stop, ticker;
var ground = [], water = [], enemies = [], environment = [];
//Platform variables
var platformHeight, platformLength, gapLength;
var platformWidth = 32;
var platformBase = canvas.height - platformWidth;
var platformSpacer = 64;
//Randomly generates a number
function random(low, high)
{
return Math.floor(Math.random() * (high - low + 1) + low);
}
//Bounds a number
function bound(num, low, high)
{
return Math.max(Math.min(num, high), low);
}
//Loads all of the assets
var assetLoader = (function()
{
this.imgs = {
'bg' : 'Images/bg.png',
'sky' : 'Images/sky.png',
'backdrop' : 'Images/backdrop.png',
'backdrop2' : 'Images/backdrop_ground.png',
'grass' : 'Images/grass.png',
'avatar_normal' : 'Images/normal_walk.png',
'water' : 'imgs/water.png',
'grass1' : 'imgs/grassMid1.png',
'grass2' : 'imgs/grassMid2.png',
'bridge' : 'imgs/bridge.png',
'plant' : 'imgs/plant.png',
'bush1' : 'imgs/bush1.png',
'bush2' : 'imgs/bush2.png',
'cliff' : 'imgs/grassCliffRight.png',
'spikes' : 'imgs/spikes.png',
'box' : 'imgs/boxCoin.png',
'slime' : 'imgs/slime.png'
};
var assetsLoaded = 0; //How many assets have been loaded
var numImgs = Object.keys(this.imgs).length; //Total number of image assets
this.totalAssest = numImgs; //Total number of assets
function assetLoaded(dic, name)
{
if(this[dic][name].status !== 'loading')
{
return;
}
this[dic][name].status = 'loaded';
assetsLoaded++;
if(assetsLoaded === this.totalAssest && typeof this.finished === 'function')
{
this.finished();
}
}
this.downloadAll = function()
{
var _this = this;
var src;
for (var img in this.imgs)
{
if (this.imgs.hasOwnProperty(img))
{
src = this.imgs[img];
(function(_this, img)
{
_this.imgs[img] = new Image();
_this.imgs[img].status = 'loading';
_this.imgs[img].name = img;
_this.imgs[img].onload = function() {assetLoaded.call(_this, 'imgs', img)};
_this.imgs[img].src = src;
})(_this, img);
}
}
}
return{
imgs: this.imgs,
totalAssest: this.totalAssest,
downloadAll: this.downloadAll
};
})();
assetLoader.finished = function()
{
startGame();
}
function SpriteSheet(path, frameWidth, frameHeight)
{
this.image = new Image();
this.frameWidth = frameWidth;
this.frameHeight = frameHeight;
var self = this;
this.image.onload = function()
{
self.framesPerRow = Math.floor(self.image.width / self.frameWidth);
};
this.image.src = path;
}
function Animation(spritesheet, frameSpeed, startFrame, endFrame)
{
var animationSequence = [];
var currentFrame = 0;
var counter = 0;
for (var frameNumber = startFrame; frameNumber <= endFrame; frameNumber++)
{
animationSequence.push(frameNumber);
}
this.update = function()
{
if (counter == (frameSpeed - 1))
{
currentFrame = (currentFrame + 1) % animationSequence.length;
}
counter = (counter + 1) % frameSpeed;
};
this.draw = function(x, y)
{
var row = Math.floor(animationSequence[currentFrame] / spritesheet.framesPerRow);
var col = Math.floor(animationSequence[currentFrame] % spritesheet.framesPerRow);
ctx.drawImage
(
spritesheet.image,
col * spritesheet.frameWidth, row * spritesheet.frameHeight,
spritesheet.frameWidth, spritesheet.frameHeight,
x, y,
spritesheet.frameWidth, spritesheet.frameHeight);
};
}
var background = (function()
{
var sky = {};
var backdrop = {};
var backdrop2 = {};
this.draw = function()
{
ctx.drawImage(assetLoader.imgs.bg, 0, 0);
sky.x -= sky.speed;
backdrop.x -= backdrop.speed;
backdrop2.x -= backdrop2.speed;
ctx.drawImage(assetLoader.imgs.sky, sky.x, sky.y);
ctx.drawImage(assetLoader.imgs.sky, sky.x + canvas.width, sky.y);
ctx.drawImage(assetLoader.imgs.backdrop, backdrop.x, backdrop.y);
ctx.drawImage(assetLoader.imgs.backdrop, backdrop.x + canvas.width, backdrop.y);
ctx.drawImage(assetLoader.imgs.backdrop2, backdrop2.x, backdrop2.y);
ctx.drawImage(assetLoader.imgs.backdrop2, backdrop2.x + canvas.width, backdrop2.y);
if (sky.x + assetLoader.imgs.sky.width <= 0)
{
sky.x = 0;
}
if (backdrop.x + assetLoader.imgs.backdrop.width <= 0)
{
backdrop.x = 0;
}
if (backdrop2.x + assetLoader.imgs.backdrop2.width <= 0)
{
backdrop2.x = 0;
}
};
this.reset = function()
{
sky.x = 0;
sky.y = 0;
sky.speed = 0.2;
backdrop.x = 0;
backdrop.y = 0;
backdrop.speed = 0.4;
backdrop2.x = 0;
backdrop2.y = 0;
backdrop2.speed = 0.6;
}
return{
draw: this.draw,
reset: this.reset
};
})();
//A vector for 2D space
function Vector(x, y, dx, dy)
{
// position
this.x = x || 0;
this.y = y || 0;
// direction
this.dx = dx || 0;
this.dy = dy || 0;
}
//Advances the vector's position
Vector.prototype.advance = function()
{
this.x += this.dx;
this.y += this.dy;
};
//Gets the minimum distance between two vectors
Vector.prototype.minDist = function(vec)
{
var minDist = Infinity;
var max = Math.max(Math.abs(this.dx), Math.abs(this.dy),Math.abs(vec.dx), Math.abs(vec.dy));
var slice = 1 / max;
var x, y, distSquared;
// get the middle of each vector
var vec1 = {}, vec2 = {};
vec1.x = this.x + this.width/2;
vec1.y = this.y + this.height/2;
vec2.x = vec.x + vec.width/2;
vec2.y = vec.y + vec.height/2;
for(var percent = 0; percent < 1; percent += slice)
{
x = (vec1.x + this.dx * percent) - (vec2.x + vec.dx * percent);
y = (vec1.y + this.dy * percent) - (vec2.y + vec.dy * percent);
distSquared = x * x + y * y;
minDist = Math.min(minDist, distSquared);
}
return Math.sqrt(minDist);
};
//The player object
var player = (function(player)
{
//Player properties
player.width = 60;
player.height = 96;
player.speed = 6;
//Jumping
player.gravity = 1;
player.dy = 0;
player.jumpDy = -10;
player.isFalling = false;
player.isJumping = false;
//Spritesheets
player.sheet = new SpriteSheet('Images/normal_walk.png', player.width, player.height);
player.walkAnim = new Animation(player.sheet, 4, 0, 15);
player.jumpAnim = new Animation(player.sheet, 4, 15, 15);
player.fallAnim = new Animation(player.sheet, 4, 11, 11);
player.anim = player.walkAnim;
Vector.call(player, 0, 0, 0, player.dy);
var jumpCounter = 0;
player.update = function()
{
//Jump if not currently jumping or falling
if(KEY_STATUS.space && player.dy === 0 && !player.isJumping)
{
player.isJumping = true;
player.dy = player.jumpDy;
jumpCounter = 12;
}
//Jump higher if the spacebar is continually pressed
if(KEY_STATUS.space && jumpCounter)
{
player.dy = player.jumpDy;
}
jumpCounter = Math.max(jumpCounter - 1, 0);
this.advance();
//Gravity
if(player.isFalling || player.isJumping)
{
player.dy += player.gravity;
}
//Falling Animation
if(player.dy > 0)
{
player.anim = player.fallAnim;
}
// change animation is jumping
else if(player.dy < 0)
{
player.anim = player.jumpAnim;
}
else
{
player.anim = player.walkAnim;
}
player.anim.update();
};
//Draw the player's current position
player.draw = function()
{
player.anim.draw(player.x, player.y);
};
//Resets the player's position
player.reset = function()
{
player.x = 64;
player.y = 250;
};
return player;
})(Object.create(Vector.prototype));
//Sprites
function Sprite(x, y, type)
{
this.x = x;
this.y = y;
this.width = platformWidth;
this.height = platformWidth;
this.type = type;
Vector.call(this, x, y, 0, 0);
//Updating the sprites
this.update = function()
{
this.dx = -player.speed;
this.advancer();
}
//Drawing the sprites
this.draw = function()
{
ctx.save();
ctx.translate(0.5, 0.5);
ctx.drawImage(assetLoader.imgs[this.type], this.x, this.y);
ctx.restore();
}
}
Sprite.prototype = Object.create(Vector.prototype);
//Platforms
function getType()
{
var type;
switch(platformHeight)
{
case 0:
case 1:
type = Math.random() > 0.5 ? 'grass1' : 'grass2';
break;
case 2:
type = 'grass';
break;
case 3:
type = 'bridge';
break;
case 4:
type = 'box';
break;
}
if (platformLength === 1 && platformHeight < 3 && rand(0, 3) === 0)
{
type = 'cliff';
}
return type;
}
//Update and draw all ground positions
function updateGround()
{
//Animate ground
player.isFalling = true;
for(var i = 0; i < ground.length; i++)
{
ground[i].update();
ground[i].draw();
//Stop the player going through the platforms when landing
var angle;
if(player.minDist(ground[i]) <= player.height/2 + platformWidth/2 && (angle = Math.atan2(player.y - ground[i].y, player.x - ground[i].x) * 180/Math.PI) > -130 &&angle < -50)
{
player.isJumping = false;
player.isFalling = false;
player.y = ground[i].y - player.height + 5;
player.dy = 0;
}
}
//Remove the ground that has gone off screen
if(ground[0] && ground[0].x < -platformWidth)
{
ground.splice(0, 1);
}
}
//Update and draw all water positions
function updateWater()
{
//Animate water
for(var i = 0; i < water.length; i++)
{
water[i].update();
water[i].draw();
}
//Remove water that has gone off screen
if (water[0] && water[0].x < -platformWidth)
{
var w = water.splice(0, 1)[0];
w.x = water[water.length-1].x + platformWidth;
water.push(w);
}
}
//Update and draw all environment positions
function updateEnvironment()
{
//Animate environment
for(var i = 0; i < environment.length; i++)
{
environment[i].update();
environment[i].draw();
}
//R emove environment that have gone off screen
if(environment[0] && environment[0].x < -platformWidth)
{
environment.splice(0, 1);
}
}
//Update and draw all enemies position. Also check for collision against the player.
function updateEnemies()
{
//Animate enemies
for(var i = 0; i < enemies.length; i++)
{
enemies[i].update();
enemies[i].draw();
//Player ran into enemy
if(player.minDist(enemies[i]) <= player.width - platformWidth/2)
{
gameOver();
}
}
//Remove enemies that have gone off screen
if(enemies[0] && enemies[0].x < -platformWidth)
{
enemies.splice(0, 1);
}
}
//Update and draw the players position
function updatePlayer()
{
player.update();
player.draw();
//Game over
if(player.y + player.height >= canvas.height)
{
gameOver();
}
}
//Spawn new sprites off screen
function spawnSprites()
{
//Increase score
score++;
//First create a gap
if(gapLength > 0)
{
gapLength--;
}
//Then create the ground
else if(platformLength > 0)
{
var type = getType();
ground.push(new Sprite(
canvas.width + platformWidth % player.speed,
platformBase - platformHeight * platformSpacer,
type
));
platformLength--;
//Add random environment sprites
spawnEnvironmentSprites();
//Add random enemies
spawnEnemySprites();
}
//Start over
else
{
//Increase gap length every speed increase of 4
gapLength = rand(player.speed - 2, player.speed);
// only allow a ground to increase by 1
platformHeight = bound(rand(0, platformHeight + rand(0, 2)), 0, 4);
platformLength = rand(Math.floor(player.speed/2), player.speed * 4);
}
}
//Spawn new environment sprites off screen
function spawnEnvironmentSprites()
{
if(score > 40 && rand(0, 20) === 0 && platformHeight < 3)
{
if (Math.random() > 0.5)
{
environment.push(new Sprite(canvas.width + platformWidth % player.speed, platformBase - platformHeight * platformSpacer - platformWidth, 'plant'));
}
else if(platformLength > 2)
{
environment.push(new Sprite(canvas.width + platformWidth % player.speed, platformBase - platformHeight * platformSpacer - platformWidth, 'bush1'));
environment.push(new Sprite(canvas.width + platformWidth % player.speed + platformWidth, platformBase - platformHeight * platformSpacer - platformWidth, 'bush2'));
}
}
}
//Spawn new enemy sprites off screen
function spawnEnemySprites()
{
if(score > 100 && Math.random() > 0.96 && enemies.length < 3 && platformLength > 5 && (enemies.length ? canvas.width - enemies[enemies.length-1].x >= platformWidth * 3 || canvas.width - enemies[enemies.length-1].x < platformWidth : true))
{
enemies.push(new Sprite(canvas.width + platformWidth % player.speed, platformBase - platformHeight * platformSpacer - platformWidth, Math.random() > 0.5 ? 'spikes' : 'slime'));
}
}
//Game Loop
function animate()
{
if(!stop)
{
requestAnimFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
background.draw();
//Update entities
updateWater();
updateEnvironment();
updatePlayer();
updateGround();
updateEnemies();
//Draw the score
ctx.fillText('Score: ' + score + 'm', canvas.width - 140, 30);
//Spawn a new Sprite
if(ticker % Math.floor(platformWidth / player.speed) === 0)
{
spawnSprites();
}
//Increase player's speed only when player is jumping
if(ticker > (Math.floor(platformWidth / player.speed) * player.speed * 20) && player.dy !== 0)
{
player.speed = bound(++player.speed, 0, 15);
player.walkAnim.frameSpeed = Math.floor(platformWidth / player.speed) - 1;
//Reset ticker
ticker = 0;
//Spawn a platform to fill in gap created by increasing player speed
if(gapLength === 0)
{
var type = getType();
ground.push(new Sprite(canvas.width + platformWidth % player.speed, platformBase - platformHeight * platformSpacer, type));
platformLength--;
}
}
ticker++;
}
}
//Spacebar events
var KEY_CODES = {
32: 'space'
};
var KEY_STATUS = {};
for(var code in KEY_CODES)
{
if(KEY_CODES.hasOwnProperty(code))
{
KEY_STATUS[KEY_CODES[code]] = false;
}
}
document.onkeydown - function(e)
{
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if(KEY_CODES[keyCode])
{
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = true;
}
};
document.onkeydown - function(e)
{
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if(KEY_CODES[keyCode])
{
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = false;
}
};
//Request Animation Polyfill
var requestAnimFrame = (function()
{
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, element)
{
window.setTimeout(callback, 1000 / 60);
};
})();
//Start the game and resets all variables and entities, spawn ground and water.
function startGame()
{
document.getElementById('game-over').style.display = 'none';
ground = [];
water = [];
environment = [];
enemies = [];
player.reset();
ticker = 0;
stop = false;
score = 0;
platformHeight = 2;
platformLength = 15;
gapLength = 0;
ctx.font = '16px arial, sans-serif';
for (var i = 0; i < 30; i++)
{
ground.push(new Sprite(i * (platformWidth-3), platformBase - platformHeight * platformSpacer, 'grass'));
}
for (i = 0; i < canvas.width / 32 + 2; i++)
{
water.push(new Sprite(i * platformWidth, platformBase, 'water'));
}
background.reset();
animate();
}
//End the game and restart
function gameOver()
{
stop = true;
document.getElementById('game-over').style.display = 'block';
}
document.getElementById('restart').addEventListener('click', startGame);
assetLoader.downloadAll();
})();

pass a random generated variable to setInterval

I have animated a dynamic created element with setInterval. When the element is clicked I want it to change to a random direction (left, right, up or down).
I think the problem is that I canĀ“t pass the randomly created direction into the setInterval function.
The html here....
<div id="klicker"></div>
The JavaScript here.....
var box = document.getElementById("klicker");
var x = 1;
var startp = 200;
box.onclick = function() {
var newdiv = document.createElement('div');
document.body.appendChild(newdiv);
newdiv.style.width = 200 + 'px';
newdiv.style.height = 200 + 'px';
newdiv.style.backgroundColor = 'grey';
newdiv.style.position = 'absolute';
newdiv.style.left = startp + "px";
newdiv.style.top = startp + "px";
newdiv.setAttribute('id', 'runner')
var run = document.getElementById('runner');
var dire = 'right';
run.onclick = function() {
var mov = function() {
randoms();
};
function randoms() {
alert('ddddd');
var rnd = (Math.random() * 4) + 1; //ranom number 1-4
var rnd_down = Math.floor(rnd); //make it en integer
/*--- make each number a uniqe direction---*/
if (rnd_down == 1) {
dire = 'right';
} else if (rnd_down == 2) {
dire = 'left';
} else if (rnd_down == 3) {
dire = 'up';
} else {
dire = 'down';
}
};
var moveit = setInterval(function() {
movefunc();
}, 50);
function movefunc() {
/*----each direction will make the div travel in diffrent directions--*/
if (dire = 'right') {
x = x + 1;
newdiv.style.left = x + 'px';
} else if (dire = 'left') {
x = x - 1;
newdiv.style.left = x + 'px';
} else if (dire = 'up') {
x = x - 1;
newdiv.style.top = x + 'px';
} else {
x = x + 1;
newdiv.style.top = x + 'px';
}
};
};
}
function movefunc() {
/*----each direction will make the div travel in diffrent directions--*/
if (dire = 'right') {
x = x + 1;
newdiv.style.left = x + 'px';
} else if (dire = 'left') {
x = x - 1;
newdiv.style.left = x + 'px';
} else if (dire = 'up') {
x = x - 1;
newdiv.style.top = x + 'px';
} else {
x = x + 1;
newdiv.style.top = x + 'px';
}
};
Rookie mistake :) ( even though it's one of the most common error in programming, see #4 ) In your condition, you should use == and not = ( which is meant for assignation, == is made for comparison ). I'd even suggest you to use === which will also compare the types. ( 1 == '1' will return true while 1 === '1' will return false cause 1 is an integer type, and '1' is a char type )

jqplotToImageCanvas not working in chrome version 47.0 and firefox 41.0.1

I have multiple charts generated by PHPChart but when i use from print option to print the chart in pdf, and png in chrome it is not working for bar chart types but work for line chart, but if there is one bar chart it works, in Firefox it is not working for vertical bar chart but work for horizontal bar chart.
all type of charts are generated dynamically using database data there is no difference in case of html wrapper tags.
when i click on export button browser hung up.
The javascript code:
function getImageData(obj, type, title)
{
var str;
imgtype = type;
if (type == 'jpg-pdf')
{
imgtype = 'jpg';
type = 'pdf';
}
var imgCanvas = $('#'+obj).jqplotToImageCanvas();
if (imgCanvas) {
str = imgCanvas.toDataURL("image/"+imgtype);
}
else {
str = null;
}
$('#pngdata').val(str);
$('#imgtype').val(type);
$('#imgtitle').val(title);
$('#imgform').submit();
}
and the jqplot function
$.fn.jqplotToImageCanvas = function(options) {
options = options || {};
var x_offset = (options.x_offset == null) ? 0 : options.x_offset;
var y_offset = (options.y_offset == null) ? 0 : options.y_offset;
var backgroundColor = (options.backgroundColor == null) ? 'rgb(255,255,255)' : options.backgroundColor;
if ($(this).width() == 0 || $(this).height() == 0) {
return null;
}
// excanvas and hence IE < 9 do not support toDataURL and cannot export images.
if ($.jqplot.use_excanvas) {
return null;
}
var newCanvas = document.createElement("canvas");
var h = $(this).outerHeight(true);
var w = $(this).outerWidth(true);
var offs = $(this).offset();
var plotleft = offs.left;
var plottop = offs.top;
var transx = 0, transy = 0;
// have to check if any elements are hanging outside of plot area before rendering,
// since changing width of canvas will erase canvas.
var clses = ['jqplot-table-legend', 'jqplot-xaxis-tick', 'jqplot-x2axis-tick', 'jqplot-yaxis-tick', 'jqplot-y2axis-tick', 'jqplot-y3axis-tick',
'jqplot-y4axis-tick', 'jqplot-y5axis-tick', 'jqplot-y6axis-tick', 'jqplot-y7axis-tick', 'jqplot-y8axis-tick', 'jqplot-y9axis-tick',
'jqplot-xaxis-label', 'jqplot-x2axis-label', 'jqplot-yaxis-label', 'jqplot-y2axis-label', 'jqplot-y3axis-label', 'jqplot-y4axis-label',
'jqplot-y5axis-label', 'jqplot-y6axis-label', 'jqplot-y7axis-label', 'jqplot-y8axis-label', 'jqplot-y9axis-label' ];
var temptop, templeft, tempbottom, tempright;
for (var i = 0, j = clses.length; i < j; i++) {
$(this).find('.'+clses[i]).each(function() {
temptop = $(this).offset().top - plottop;
templeft = $(this).offset().left - plotleft;
tempright = templeft + $(this).outerWidth(true) + transx;
tempbottom = temptop + $(this).outerHeight(true) + transy;
if (templeft < -transx) {
w = w - transx - templeft;
transx = -templeft;
}
if (temptop < -transy) {
h = h - transy - temptop;
transy = - temptop;
}
if (tempright > w) {
w = tempright;
}
if (tempbottom > h) {
h = tempbottom;
}
});
}
newCanvas.width = w + Number(x_offset);
newCanvas.height = h + Number(y_offset);
var newContext = newCanvas.getContext("2d");
newContext.save();
newContext.fillStyle = backgroundColor;
newContext.fillRect(0,0, newCanvas.width, newCanvas.height);
newContext.restore();
newContext.translate(transx, transy);
newContext.textAlign = 'left';
newContext.textBaseline = 'top';
function getLineheight(el) {
var lineheight = parseInt($(el).css('line-height'), 10);
if (isNaN(lineheight)) {
lineheight = parseInt($(el).css('font-size'), 10) * 1.2;
}
return lineheight;
}
function writeWrappedText (el, context, text, left, top, canvasWidth) {
var lineheight = getLineheight(el);
var tagwidth = $(el).innerWidth();
var tagheight = $(el).innerHeight();
var words = text.split(/\s+/);
var wl = words.length;
var w = '';
var breaks = [];
var temptop = top;
var templeft = left;
for (var i=0; i<wl; i++) {
w += words[i];
if (context.measureText(w).width > tagwidth && w.length > words[i].length) {
breaks.push(i);
w = '';
i--;
}
}
if (breaks.length === 0) {
// center text if necessary
if ($(el).css('textAlign') === 'center') {
templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
}
context.fillText(text, templeft, top);
}
else {
w = words.slice(0, breaks[0]).join(' ');
// center text if necessary
if ($(el).css('textAlign') === 'center') {
templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
}
context.fillText(w, templeft, temptop);
temptop += lineheight;
for (var i=1, l=breaks.length; i<l; i++) {
w = words.slice(breaks[i-1], breaks[i]).join(' ');
// center text if necessary
if ($(el).css('textAlign') === 'center') {
templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
}
context.fillText(w, templeft, temptop);
temptop += lineheight;
}
w = words.slice(breaks[i-1], words.length).join(' ');
// center text if necessary
if ($(el).css('textAlign') === 'center') {
templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
}
context.fillText(w, templeft, temptop);
}
}
function _jqpToImage(el, x_offset, y_offset) {
var tagname = el.tagName.toLowerCase();
var p = $(el).position();
var css = window.getComputedStyle ? window.getComputedStyle(el, "") : el.currentStyle; // for IE < 9
var left = x_offset + p.left + parseInt(css.marginLeft, 10) + parseInt(css.borderLeftWidth, 10) + parseInt(css.paddingLeft, 10);
var top = y_offset + p.top + parseInt(css.marginTop, 10) + parseInt(css.borderTopWidth, 10)+ parseInt(css.paddingTop, 10);
var w = newCanvas.width;
// var left = x_offset + p.left + $(el).css('marginLeft') + $(el).css('borderLeftWidth')
// somehow in here, for divs within divs, the width of the inner div should be used instead of the canvas.
if ((tagname == 'div' || tagname == 'span') && !$(el).hasClass('jqplot-highlighter-tooltip')) {
$(el).children().each(function() {
_jqpToImage(this, left, top);
});
var text = $(el).jqplotChildText();
if (text) {
newContext.font = $(el).jqplotGetComputedFontStyle();
newContext.fillStyle = $(el).css('color');
writeWrappedText(el, newContext, text, left, top, w);
}
}
// handle the standard table legend
else if (tagname === 'table' && $(el).hasClass('jqplot-table-legend')) {
newContext.strokeStyle = $(el).css('border-top-color');
newContext.fillStyle = $(el).css('background-color');
newContext.fillRect(left, top, $(el).innerWidth(), $(el).innerHeight());
if (parseInt($(el).css('border-top-width'), 10) > 0) {
newContext.strokeRect(left, top, $(el).innerWidth(), $(el).innerHeight());
}
// find all the swatches
$(el).find('div.jqplot-table-legend-swatch-outline').each(function() {
// get the first div and stroke it
var elem = $(this);
newContext.strokeStyle = elem.css('border-top-color');
var l = left + elem.position().left;
var t = top + elem.position().top;
newContext.strokeRect(l, t, elem.innerWidth(), elem.innerHeight());
// now fill the swatch
l += parseInt(elem.css('padding-left'), 10);
t += parseInt(elem.css('padding-top'), 10);
var h = elem.innerHeight() - 2 * parseInt(elem.css('padding-top'), 10);
var w = elem.innerWidth() - 2 * parseInt(elem.css('padding-left'), 10);
var swatch = elem.children('div.jqplot-table-legend-swatch');
newContext.fillStyle = swatch.css('background-color');
newContext.fillRect(l, t, w, h);
});
// now add text
$(el).find('td.jqplot-table-legend-label').each(function(){
var elem = $(this);
var l = left + elem.position().left;
var t = top + elem.position().top + parseInt(elem.css('padding-top'), 10);
newContext.font = elem.jqplotGetComputedFontStyle();
newContext.fillStyle = elem.css('color');
writeWrappedText(elem, newContext, elem.text(), l, t, w);
});
var elem = null;
}
else if (tagname == 'canvas') {
newContext.drawImage(el, left, top);
}
}
$(this).children().each(function() {
_jqpToImage(this, x_offset, y_offset);
});
return newCanvas;
};
kindly help me.

Add links to images in array

I'm trying to add links to the images in my JS array so that, when clicked, they direct you to a info page.
I tried to use the following code but the images won't show.
var WorkArray = new Array(['work/01.png',"http://www.stackoverflow.com"],
['work/02.png',"http://www.stackoverflow.com"],
['work/03.png',"http://www.stackoverflow.com"],
['work/04.png',"http://www.stackoverflow.com"]);
If I remove the links the images do show.
I'm using a variation of this code: http://bouncingdvdlogo.com/
Here is my full code:
var width = 400;
var height = 400;
var swoosh = 4;
var stopafter=0; //set time in seconds before image disappears. Use 0 for never
var maxswoosh = 50;
var xMax;
var yMax;
var xPos = 0;
var yPos = 0;
var xDir = 'right';
var yDir = 'down';
var screenSavouring = true;
var tempswoosh;
var newXDir;
var newYDir;
function setupShit() {
if (document.all) {
xMax = document.body.clientWidth
yMax = document.body.clientHeight
document.all("work").style.visibility = "visible";
}
else if (document.layers||document.getElementById) {
xMax = window.innerWidth-0;
yMax = window.innerHeight;
if (document.getElementById)
document.getElementById("work").style.visibility="visible"
else
document.layers["work"].visibility = "show";
}
setTimeout('moveIt()',500);
}
function moveIt() {
if (screenSavouring == true) {
calculatePosition();
if (document.all) {
document.all("work").style.left = xPos + document.body.scrollLeft;
document.all("work").style.top = yPos + document.body.scrollTop;
}
else if (document.layers) {
document.layers["work"].left = xPos + pageXOffset;
document.layers["work"].top = yPos + pageYOffset;
}
else if (document.getElementById) {
document.getElementById("work").style.left = xPos + pageXOffset;
document.getElementById("work").style.top = yPos + pageYOffset;
}
doit=setTimeout('moveIt()',30);
}
}
function calculatePosition() {
if (xDir == "right") {
if (xPos > (xMax - width - swoosh)) {
xDir = "left";
cC();
}
}
else if (xDir == "left") {
if (xPos < (0 + swoosh)) {
xDir = "right";
cC();
}
}
if (yDir == "down") {
if (yPos > (yMax - height - swoosh)) {
yDir = "up";
cC();
}
}
else if (yDir == "up") {
if (yPos < (0 + swoosh)) {
yDir = "down";
cC();
}
}
if (xDir == "right") {
xPos = xPos + swoosh;
}
else if (xDir == "left") {
xPos = xPos - swoosh;
}
else {
xPos = xPos;
}
if (yDir == "down") {
yPos = yPos + swoosh;
}
else if (yDir == "up") {
yPos = yPos - swoosh;
}
else {
yPos = yPos;
}
}
if (document.all||document.layers||document.getElementById){
window.onload = setupShit;
window.onresize = new Function("window.location.reload()");
}
var WorkArray = new Array(['work/01.png',"http://www.stackoverflow.com", "Your text goes here"],
['work/02.png',"http://www.stackoverflow.com", "Your text goes here"],
['work/03.png',"http://www.stackoverflow.com", "Your text goes here"],
['work/04.png',"http://www.stackoverflow.com", "Your text goes here"]);
var nelements = WorkArray.length;
preload_image_object = new Image();
var i = 0;
for(i=0; i<=nelements; i++) {
preload_image_object.src = WorkArray[i];
}
var currentImage = 0
function cC() {
currentImage = (currentImage + 1) % WorkArray.length;
document.getElementById("work").style.backgroundImage="url('"+WorkArray[currentImage]+"')";
}
Thanks!
Try replacing your for loop with below
for(i=0; i<nelements; i++) {
preload_image_object.src = WorkArray[i][0];
}
Also Replace function cC() with below:
function cC() {
var nelements = WorkArray.length;
var rdmnum = Math.floor(Math.random() * nelements);
var currentImage = rdmnum++;
if (currentImage == nelements) {
rdmnum = Math.floor(Math.random() * nelements);
}
currentImage = (currentImage + 1) % WorkArray.length;
document.getElementById("work").style.backgroundImage = "url('" + WorkArray[currentImage][0] + "')";
}

Categories