Add links to images in array - javascript

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] + "')";
}

Related

How can i make the bullet not move with the character when looking either right or left?

I am having a problem where when I fire either left or right, once i move the character the bullets direction will change while its still fired. I am using the protagonist picture as the condition to either shoot right or left but i would like the bullet to keep firing in the fired direction even if i change the movement of the character
I am a beginner in Javascript and I'm using canvas to create a game for a college project.
if (moveBullet) {
let s = heroPic.src.substring(heroPic.src.lastIndexOf("/") + 1);
//alert(s);
if (s == "Protagenist_Right_Jet.png" || s == "Protagenist_Stand_Jet.png") {
bulletX += 20;
}
if (s == "Protagenist_Left_Jet.png") {
bulletX -= 20;
}
if (bulletX >= canvas.width) {
moveBullet = false;
bulletX = canvas.width + 50
bulletY = canvas.height + 50;
}
if (bulletX <= 0) {
moveBullet = false;
bulletX = canvas.width + 50
bulletY = canvas.height + 50;
}
}
Full Code
<!DOCTYPE html>
<body>
<div id="canvasesdiv" style="text-align: center;">
<canvas id="canvas1" width="800" height="500" tabIndex="0" style="background: url('Level 1.png');position: relative; display: block;">
</div>
<script>
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
//get the animation frame depending on the browser engine
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
//Hero Attributes
var jetPackAudio = new Audio();
jetPackAudio.src = "Jetpack Sound.mp3";
var heroPic = new Image();
var heroX ;
var heroY ;
//Decides where the hero is looking
var heroRight = false;
var life = 3;
var heroWidth = 50 ;
var heroHeight = 50 ;
var gravity = 5;
heroX = 20;
heroY = 440;
heroPic.src = "Protagenist_Stand_Jet.png";
function drawHero(x,y)
{
ctx.drawImage(heroPic,x,y,heroWidth,heroHeight);
}
hitBottom = function() {
var rockbottom = canvas.height - heroHeight;
if (heroY > rockbottom) {
heroY = rockbottom;
}
}
// Key Attribute
var key = new Image();
key.src = "Key1.png"
var keyX ;
var keyY ;
var keyCounter = 0;
var keyWidth = 30 ;
var keyHeight = 30 ;
function drawKey()
{
ctx.drawImage(key,keyX,keyY,keyWidth,keyHeight);
}
var killCounter = 0 ;
var levelKillCounter;
// Monster 1 Attributes
var monster1 = new Image();
monster1.src = "Monster1_Left.png"
var m1MoveLeft = true;
var m1X ;
var m1Y ;
var m1Width = 50 ;
var m1Height = 50 ;
function drawMonster1()
{
ctx.drawImage(monster1,m1X,m1Y,m1Width,m1Height);
}
// Monster 2 Attributes
var monster2 = new Image();
monster2.src = "Monster 2_Right.png"
var m2MoveRight = true;
var m2X ;
var m2Y ;
var m2Width = 50 ;
var m2Height = 50 ;
function drawMonster2()
{
ctx.drawImage(monster2,m2X,m2Y,m2Width,m2Height);
}
// Monster 3 Attributes
var monster3 = new Image();
monster3.src = "Monster3_Right.png"
var m3MoveRight = true;
var m3X ;
var m3Y ;
var m3Width = 50 ;
var m3Height = 50 ;
function drawMonster3()
{
ctx.drawImage(monster3,m3X,m3Y,m3Width,m3Height);
}
// Hit Bottom
hitBottom = function() {
var rockbottom = canvas.height - heroHeight;
if (heroY > rockbottom) {
heroY = rockbottom;
}
}
//Bullet Attribute
var bulletX;
var bulletY;
const ammo = [];
var moveBullet = false;
var bulletImage = new Image();
bulletImage.src = 'Bullet.png';
function drawBullet(x,y)
{
ctx.drawImage(bulletImage,bulletX,bulletY);
}
//this function is used to detect a hit monster 1
function getDistanceHit1() {
var xRect = (m1X - bulletX);
var yRect = (m1Y - bulletY);
return Math.sqrt(Math.pow((xRect), 2) + Math.pow((yRect), 2));
}
//this function is used to detect a hit monster 2
function getDistanceHit2() {
var xRect = (m2X - bulletX);
var yRect = (m2Y - bulletY);
return Math.sqrt(Math.pow((xRect), 2) + Math.pow((yRect), 2));
}
//this function is used to detect a hit monster 3
function getDistanceHit3() {
var xRect = (m3X - bulletX);
var yRect = (m3Y - bulletY);
return Math.sqrt(Math.pow((xRect), 2) + Math.pow((yRect), 2));
}
//this function is used to detect if the player got the key
function getDistanceKey() {
var xRect = (keyX - heroX);
var yRect = (keyY - heroY);
return Math.sqrt(Math.pow((xRect), 2) + Math.pow((yRect), 2));
}
//configure the audio files
var fireAudio = new Audio();
fireAudio.src = "fire.mp3";
var hitAudio = new Audio();
hitAudio.src = "neck_snap.wav"
//Hero Movement
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
window.addEventListener("keydown", heroControl);
//Keyboard Cotrolls
function heroControl(event) { //event handler function
if (event.keyCode == 32) { //SPACE BAR PRESSED - fire gun
moveBullet = true;
fireAudio.play();
bulletX = heroX + 10;
bulletY = heroY + (heroHeight / 2);
console.log("BulletX = " + bulletX);
}
// 38 is up arrow, 87 is the W key
if (event.keyCode == 38 || event.keyCode == 87) { //Jump
upPressed = true;
console.log("HeroY = " + heroY);
}
// 39 is right arrow, 68 is thw D key
else if (event.keyCode == 39 || event.keyCode == 68) { //move Right
rightPressed = true;
console.log("Herox = " + heroX);
}
else if(event.keyCode == 37 || event.keyCode == 65) { // Move Left
leftPressed = true;
console.log("Herox = " + heroX);
}
else if(event.keyCode == 40 || event.keyCode == 83) { // Move Left
downPressed = true;
console.log("Heroy = " + heroY);
}
}
//Touch Controls
canvas.addEventListener("touchstart", handleTouchStart, false);
function handleTouchStart(touchEvent) { //event handler for touch events
var rect = canvas.getBoundingClientRect(); //to get canvas offsets
let touchX = touchEvent.changedTouches[0].clientX - rect.left;
let touchY = touchEvent.changedTouches[0].clientY - rect.top;
if (touchX <= canvas.width && touchX > canvas.width - 200) {
rightPressed = true;
}
if (touchX >= 0 && touchX < canvas.width - 600) {
leftPressed = true;
}
if (touchY >= 0 && touchY < canvas.height - 200) {
upPressed = true;
}
if (touchY <= canvas.height && touchY > canvas.height - 200) {
downPressed = true;
}
}
function moveHero() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if(rightPressed) {
if(heroX < canvas.width - 53){
heroPic.src = "Protagenist_Right_Jet.png"
heroRight = true;
heroX = heroX + 10;
heroRight = true;
rightPressed = false;
}
else
{
rightPressed = false;
heroRight = false;
}
}
if(leftPressed) {
if(heroX > 0){
heroX = heroX - 10;
heroLeft = true;
heroPic.src = "Protagenist_Left_Jet.png";
bulletImage.src = "left_bullet.png";
leftPressed = false;
}
else
{
leftPressed = false;
heroLeft = false;
}
}
if(upPressed) {
if(heroY > 0){
heroY = heroY - 20;
heroStand = true;;
jetPackAudio.play();
heroPic.src = "Protagenist_Stand_Jet.png";
upPressed = false;
}
else
{
upPressed = false;
heroStand = false;;
}
}
if(downPressed) {
if(heroY < canvas.height){
heroPic.src = "Protagenist_Stand_Jet.png"
heroStand = true;
heroY = heroY + 10;
downPressed = false;
}
else
{
downPressed = false;
heroStand = false;
}
}
displayScoreArea();
drawHero(heroX,heroY);
drawMonster1();
drawMonster2();
drawMonster3();
drawKey();
drawBullet(bulletX,bulletY);
requestAnimationFrame(moveHero);
}
//Level Setter
var level = 2;
function setLvl()
{
if(level == 1)
{
canvas.style = "background: url('Level 1.png')";
levelKillCounter = 3;
}
else if(level == 2)
{
canvas.style = "background: url('Level 2.png')";
monster1.src = "Monster3_Right.png"
monster2.src = "Monster3_Right.png"
}
else if(level == 3)
{
canvas.style = "background: url('Level 3.png')";
}
}
var gameAudio = new Audio();
gameAudio.src = "Dungeon Theme.mp3"
function animation()
{
setTimeout(() => {
//animation code goes into this anonymous function handler
requestAnimationFrame(animation);
//clear the whole canvas area
ctx.clearRect(0, 0, canvas.width, canvas.height);
moveHero();
drawMonster1();
drawMonster2();
drawMonster3();
drawKey();
drawBullet(bulletX,bulletY);
monsterAnimate();
setLvl();
heroY = heroY + gravity;
if(moveBullet)
{
let s = heroPic.src.substring(heroPic.src.lastIndexOf("/") + 1);
//alert(s);
if(s == "Protagenist_Right_Jet.png" || s == "Protagenist_Stand_Jet.png")
{
bulletX +=20;
}
if(s == "Protagenist_Left_Jet.png")
{
bulletX -=20;
}
if(bulletX >= canvas.width)
{
moveBullet = false;
bulletX = canvas.width + 50
bulletY = canvas.height +50;
}
if(bulletX <= 0)
{
moveBullet = false;
bulletX = canvas.width + 50
bulletY = canvas.height +50;
}
console.log(getDistanceHit1());
if (getDistanceHit1() <= 30 ||
getDistanceHit2() <= 30 ||
getDistanceHit3() <= 30 )
{
//Delete Monster
if(getDistanceHit1() <= 30)
{
m1X = 1000;
m1Y = 1000;
}
if(getDistanceHit2() <= 30)
{
m2X = 1000;
m2Y = 1000;
}
if(getDistanceHit3() <= 30)
{
m3X = 1000;
m3Y = 1000;
}
//increase the hit count
killCounter++;
//we have a hit
moveBullet = false;
//play the hitAudio
hitAudio.play();
//Reset Bullet
bulletX = canvas.width + 50
bulletY = canvas.height +50;
}
}
if(killCounter == 3)
{
keyX = canvas.width / 2;
keyY = 150;
}
if(getDistanceKey() <= 10)
{
keyCounter = 1;
keyX = 1000;
keyY = 1000;
}
//level progression flow - check of level objectives are met
if (level == 1 && keyCounter == 1 && heroX >= 700 & heroY >= 50) {
alert("Level 1 completed. Starting Level 2...");
level = 2;
killCounter = 0; //reset
keyCounter = 0;//reset
m1X = 700;
m1Y = 370;
m2X = 100;
m2Y = 320;
m3X = 100;
m3Y = 170;
}
else if (level == 2 && keyCounter == 1 && heroX == 700 & heroY == 50) {
alert("Level 2 completed. Starting Level 3...");
level = 3;
killCounter = 0; //reset
keyCounter = 0;//reset
}
else if (level == 3 && currentLevelHits == 4) {
//last level
var playAgain = confirm("Game completed. Play again?");
if (playAgain)
window.location.reload(true); //force reload
else
stopAnimation = true;
}
//gameAudio.play();
displayScoreArea();
hitBottom();
},100)
}
m1X = 700;
m1Y = 370;
m2X = 100;
m2Y = 320;
m3X = 100;
m3Y = 170;
function monsterAnimate()
{
//Movement for level 1
if(level == 1)
{
if(m1MoveLeft)
{
m1X -= 10
}
else if(!m1MoveLeft)
{
m1X += 10
}
if(m2MoveRight)
{
m2X += 10
}
else if(!m2MoveRight)
{
m2X -= 10
}
if(m3MoveRight)
{
m3X +=10
}
else if(!m3MoveRight)
{
m3X -= 10
}
if(m1X == 420)
{
m1MoveLeft = false;
monster1.src ="Monster 1_Right.png"
}
else if(m1X == 700)
{
m1MoveLeft = true;
monster1.src ="Monster1_Left.png"
}
if(m2X == 310)
{
m2MoveRight = false;
monster2.src ="Monster2_left.png"
}
else if(m2X == 100)
{
m2MoveRight = true;
monster2.src ="Monster 2_Right.png"
}
if(m3X == 310)
{
m3MoveRight = false;
monster3.src ="Monster 3_left.png"
}
else if(m3X == 100)
{
m3MoveRight = true;
monster3.src ="Monster3_Right.png"
}
}
//Movement for level 2
if(level == 2)
{
if(m1MoveLeft)
{
m1X -= 20
}
else if(!m1MoveLeft)
{
m1X += 20
}
if(m2MoveRight)
{
m2X += 20
}
else if(!m2MoveRight)
{
m2X -= 20
}
if(m3MoveRight)
{
m3X +=20
}
else if(!m3MoveRight)
{
m3X -= 20
}
if(m1X == 420)
{
m1MoveLeft = false;
monster1.src ="Monster 1_Right.png"
}
else if(m1X == 700)
{
m1MoveLeft = true;
monster1.src ="Monster1_Left.png"
}
if(m2X == 600)
{
m2MoveRight = false;
monster2.src ="Monster2_left.png"
}
else if(m2X == 100)
{
m2MoveRight = true;
monster2.src ="Monster 2_Right.png"
}
if(m3X == 500)
{
m3MoveRight = false;
monster3.src ="Monster 3_left.png"
}
else if(m3X == 100)
{
m3MoveRight = true;
monster3.src ="Monster3_Right.png"
}
}
}
// Create gradient
var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
gradient.addColorStop("0", "black");
gradient.addColorStop("0.5", "red");
gradient.addColorStop("1.0", "white");
//Draw Score Area
function displayScoreArea() {
ctx.font = "40px Arial";
ctx.strokeStyle = gradient;
ctx.fillStyle = gradient;
ctx.strokeText(killCounter, 380, 60);
ctx.strokeText(life, 65, 45);
ctx.strokeText(keyCounter, 65, 90);
}
animation();
function moveup()
{
upPressed = true;
}
function movedown()
{
downPressed = true;
}
function moveright()
{
rightPressed = true;
}
function moveleft()
{
leftPressed = true;
}
function shootGun()
{
moveBullet = true;
fireAudio.play();
bulletX = heroX + 10;
bulletY = heroY + (heroHeight / 2);
console.log("BulletX = " + bulletX);
}
</script>
<div style="text-align:center;width:900px;">
<button style="width: 100px; height: 60px;" onclick="moveup()">UP</button><br><br>
<button style="width: 100px; height: 60px;" onclick="moveleft()">LEFT</button>
<button style="width: 100px; height: 60px; margin-left: 20px;" onclick="moveright()">RIGHT</button><br><br>
<button style="width: 100px; height: 60px;" onclick="movedown()">DOWN</button>
<button style="width: 100px; height: 60px;" onclick="shootGun()">SHOOT</button>
</div>
</body>
</html>
Using objects would be one (of many) steps in the right direction. Even without them, you could:
In your bullet variable creation
...
//Bullet Attribute
let bulletX;
let bulletY;
let bulletVelocity;
...
In your hero control function, where the firing action currently takes place, initialize your bullet properties once
...
//Keyboard Cotrolls
function heroControl(event) { //event handler function
if (event.keyCode == 32) { //SPACE BAR PRESSED - fire gun
moveBullet = true;
fireAudio.play();
bulletX = heroX + 10;
bulletY = heroY + (heroHeight / 2);
// Initialize bullet velocity
let s = heroPic.src.substring(heroPic.src.lastIndexOf("/") + 1);
//alert(s);
if (s == "Protagenist_Right_Jet.png" || s == "Protagenist_Stand_Jet.png") {
bulletVelocity = 20;
} else {
bulletVelocity = -20;
}
...
In your animation function, where this currently takes place, update your bullet position according to its velocity
...
if (moveBullet) {
bulletX += bulletVelocity;
if (bulletX >= canvas.width) {
...
There are lots of things I would refactor in your current setup, but this should get you moving on your current problem.
And a quick example of a very simple object:
// create with key: value pairs
let bullet = {
x: 0,
y: 0,
velocity: 0,
};
// Access or set properties using dot notation
bullet.x = heroX + 10;
bullet.y = heroY + (heroHeight / 2);

How to grab X POS every time image is added document.createElement("img");

EXAMPLE PIC
I have a problem getting X every time. When it grabs doc2.left a couple of times, it then stops and stays at 0. So the problem is, gX1 will stay at 0 after the first couple of times it graps doc2.left.
It reaches the edged of the page(even when the web page is not maximized) it stops reading doc2.left.
Any Ideas?
var cTAdd = 0;
var setThis = 1;
var GAPlayer = 3;
var gX1 = 0;
var gX2 = 0;
var gX3 = 0;
var gX4 = 0;
var gX5 = 0;
var gX6 = 0;
var getX1 = 0;
var getX2 = 0;
var getX3 = 0;
var getX4 = 0;
var getX5 = 0;
var getX6 = 0;
var getH = 0;
//////////////////////////////////////////////////////////
//
// MOVE PLATFORMS
var cFunc = 0;
function landT() {
setThis = setTimeout(landT, 400);
cTAdd = Math.floor(Math.random() * 100 + 1);
///////////////////////////////////////////////////////////////////////////
//
// BOTTOM ROW
var block00 = document.createElement("img");
var block02 = document.createElement("img"); // ADD SEPERATION BLOCK(BLOCK HOLE)
if (cTAdd > 0 && cTAdd < 40) {
block00.src = "images/sep2.png";
}
if (cTAdd > 40 && cTAdd < 80) {
block02.src = "images/sep1.png"; // ADD SEPERATION BLOCK(BLOCK HOLE)
}
if (cTAdd > 80 && cTAdd < 100) {
block00.src = "images/platform00.png";
}
document.getElementById("land01").appendChild(block00);
document.getElementById("land01").appendChild(block02); // APPEND CHILD(BLOCK HOLE)
///////////////////////////////////////////////////////////////////////////
//
// BLOCK02 GET X POS OF ADDED BLOCK
if (getX1 == 0) { //////////////////////////////////////////// SET (BLOCK HOLE) X
var doc2 = block02.getBoundingClientRect();
gX1 = doc2.left;
getX1 = 1;
}
///////////////////////////////////////////////////////////////////////////
//
// TOP ROW
var block01 = document.createElement("img");
if (cTAdd > 0 && cTAdd < 25) {
block01.src = "images/platform00.png";
}
if (cTAdd > 25 && cTAdd < 50) {
block01.src = "images/sep2.png";
}
if (cTAdd > 50 && cTAdd < 100) {
block01.src = "images/sep1.png";
}
document.getElementById("land00").appendChild(block01);
GAPlayer = GAPlayer + 3; // SET PLAYER DOCUMENT.IMAGES[]
}
//////////////////////////////////////////////////////////
//
// MOVE PLATFORMS
var thisSet = 1;
var cPlayer = 0;
var moveSpeed = 5;
var xPos = 50;
var yPos = 300;
function moveLand() {
thisSet = setTimeout(moveLand, 30);
if (xPos >= 350 && moveL == 1) {
moveBlock1 = moveBlock1 - 15;
document.getElementById("land00").style.left = moveBlock1 + "px";
document.getElementById("land01").style.left = moveBlock1 + "px";
}
///////////////////////////////////////////////
//
// X POSITION OF (BLOCK HOLE)
if (gX1 > 0 && movePR == 1 && xPos >= 350) {
gX1 = gX1 - 15;
}
if (getX1 == 1 && gX1 == 0) {
getX1 = 0;
}
if (gX1 < 0) {
gX1 = 0;
}
console.log("X1: " + gX1); // CONSOLE/LOG gX1
}
//////////////////////////////////////////////////////////
//
// MOVE PLAYER
var setP = 1;
var yMax = 18;
function moveP() {
setP = setTimeout(moveP, 10);
if (movePR == 1) {
movePL = 0;
xPos = xPos + moveSpeed;
cPlayer++;
if (cPlayer >= 4)
cPlayer = 0;
document.images[GAPlayer].src = gPlayer[cPlayer].src;
}
if (movePL == 1) {
movePR = 0;
xPos = xPos - moveSpeed;
cPlayer++;
if (cPlayer >= 4)
cPlayer = 0;
document.images[GAPlayer].src = gPlayer[cPlayer].src;
}
if (movePU == 1) {
yMax--;
yPos = yPos -= yMax
}
if (yMax <= 0) {
movePU = 2;
}
if (movePU == 2) {
yMax++;
yPos = yPos += yMax;
}
if (yMax >= 18) {
movePU = 0;
}
if (yPos >= 300) {
yPos = 300;
}
document.getElementById("player").style.left = xPos + "px";
document.getElementById("player").style.top = yPos + "px";
if (xPos >= 350) {
xPos = 350;
}
if (xPos <= 50) {
xPos = 50;
}
}

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.

Gradual Increase/Decrease javascript 2 elements

I'm trying to gradually increase the elements of 2 id's in javascript using a Interval.
I'm passing two id's for the elements. I'm trying write conditionals so that depending on the position the width of the elements gradually increase in the direction dependent of the position.
if the passed element position is smaller than the oldPosition I want the the left element to decrease and the right element to increase gradually. And the opposite if the passed element position is bigger than the oldPosition.
Note this, is an extension of my old problem which was fixed :) (Javascript gradual width increase)
Heres what ive got
function grow(elementL, elementR, elementText, position)
{
window.loopTimer = setInterval(function() {
growInner(elementL, elementR, position);
/* fadeOut(elementText); */
}, 25);
}
var oldPosition = 0;
function growInner(elementL, elementR, position)
{
var htL = parseInt(document.getElementById(elementL).style.width,10);
var htR = parseInt(document.getElementById(elementR).style.width,10);
var movementL =0;
var movementR =0;
if(position < oldPosition)
{
movementL = htL + 10;
movementR = htR - 10;
}
if(position > oldPosition)
{
movementL = htL - 10;
movementR = htR + 10;
}
if(position == 1 && htL < 600 || rtL > 250){
document.getElementById(elementL).style.width = movementL + 'px';
document.getElementById(elementR).style.width = movementR + 'px';
oldPosition = position;
}
else if(position == 2 && htL < 550 || rtL > 300){
document.getElementById(elementL).style.width = movementL + 'px';
document.getElementById(elementR).style.width = movementR + 'px';
oldPosition = position;
}
else if(position == 3 && htL < 300 || rtL > 550){
document.getElementById(elementL).style.width = movementL + 'px';
document.getElementById(elementR).style.width = movementR + 'px';
oldPosition = position;
}
else if(position == 4 && htL < 250 || rtL > 600){
document.getElementById(elementL).style.width = movementL + 'px';
document.getElementById(elementR).style.width = movementR + 'px';
oldPosition = position;
}
else{
clearInterval(loopTimer);
return false;
}
}
My previous code position conditionals were not correctly taking into account the width growth direction in terms of the position clicked. I reduced the variable documnentGet calls and added some security with the boolean returns so that it couldn't start another timer until the previous one had stopped.
I have a jsFiddle link for it but I cannot seem to get it working.
http://jsfiddle.net/2mRsG/3/
function moveStart(elementL, elementR, position)
{
var moveTimer = setInterval(function() {
if (!movingProcess(elementL, elementR, position)) {
clearInterval(moveTimer);
}
}, 20);
}
var oldPos = 1;
function movingProcess(elementL, elementR, position) {
moving = true;
var htL = parseInt(document.getElementById(elementL).style.width,10);
var htR = parseInt(document.getElementById(elementR).style.width,10);
var left = document.getElementById(elementL);
var right = document.getElementById(elementR);
if(position==1){
var movementL = htL + 5;
var movementR = htR - 5;
left.style.width = movementL + 'px';
right.style.width = movementR + 'px';
if (movementL >= 600 && position==1)
{
oldPos = 1;
moving = false;
return false;
}
}
else if(position==2 && oldPos > 2){
var movementL = htL + 5;
var movementR = htR - 5;
left.style.width = movementL + 'px';
right.style.width = movementR + 'px';
if (movementL >= 500)
{
oldPos = 2;
moving = false;
return false;
}
}
else if(position==2 && oldPos == 1){
var movementL = htL - 5;
var movementR = htR + 5;
left.style.width = movementL + 'px';
right.style.width = movementR + 'px';
if (movementR >= 300)
{
oldPos = 2;
moving = false;
return false;
}
}
else if(position==3 && oldPos < 3){
var movementL = htL - 5;
var movementR = htR + 5;
left.style.width = movementL + 'px';
right.style.width = movementR + 'px';
if (movementR >= 500)
{
oldPos = 3;
moving = false;
return false;
}
}
else if(position==3 && oldPos ==4){
var movementL = htL + 5;
var movementR = htR - 5;
left.style.width = movementL + 'px';
right.style.width = movementR + 'px';
if (movementL >= 300)
{
oldPos = 3;
moving = false;
return false;
}
}
else if(position==4){
var movementL = htL - 5;
var movementR = htR + 5;
left.style.width = movementL + 'px';
right.style.width = movementR + 'px';
if (movementR >= 600)
{
oldPos = 4;
moving = false;
return false;
}
}
return true;
}

Javascript tooltip positioning

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

Categories