3

I am trying to create an array of values using a for loop in JavaScript with multiple div id's with successive numbers (i.e. their values) denoting depth. The issue that I am running into is that I can't add the DOM element, i.e. 'text by ship here' successfully to the stage. I added // to show different sections where I am stuck. In particular, I believe I am stuck on the for loop part of the code below //Trying to create a div array here with id's q0, q1, q2, ..., q3 and have used different functions such as for div[0].setAttribute("id", "q0") to be able to connect it with the create.jsDOMElement to add this text to the stage. Any help would be extremely appreciated! My apologies in advance if the code is too long. I have tried to express it succinctly.

<html>
<script type="text/javascript" src="//code.createjs.com/createjs-2013.09.25.combined.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#gameCanvas {
  background-color: lightblue;
}
</style>
<div class="canvasHolder1">
  <div id="ship">⛵ </div> 
<script>
</script>
<canvas id="gameCanvas" width="300" height="300">Not supported</canvas>
<script type="text/javascript">

var stage = new createjs.Stage("gameCanvas");
//Trying to create a div array here with id's q0, q1, q2, ..., q3
   var div = [];
   for(i=0; i<=3; i++){
   div[i] = document.createElement("type");
   div[i].id = `q${i}`;
   div[i].innerHTML = 'text by ship here';
   document.body.appendChild(div[i]);
   }
   //Creating an object array of div elements to add to the stage
  var objectArray = [];
  objectArray[0] = new createjs.DOMElement(document.getElementById("q0"));
  var object = new createjs.DOMElement(document.getElementById("ship"));
  can = document.getElementById("gameCanvas");
  object.x = can.width/3;
  object.y = 50;
  //Adding First Value to the Stage
  objectArray[0].x= can.width/3;
  objectArray[0].y = 55;
  function startGame() {
            stage.addChild(object);
            stage.addChild(objectArray[0]);
           
            createjs.Ticker.addEventListener("tick", handleTick);
              function handleTick(event) {
              drop();
              stage.update();
            }
        }
  function drop(){
  if ( object.y>=can.height){
      object.x += 0;
      object.y +=5;
   }
 }
 
</script>
<body onload="startGame();">
    <div >
  <canvas>This browser or document mode doesn't support canvas object.</canvas>
    </div>
</body>
</html>

I have been able to make some progress on this. I am now running into the issue with the numbers needing to appear relative to the pixel 0, 0 on the Canvas/screen now, i.e. see the word relative.

<h1> I have some text here, and I need the numbers to appear relative to the Canvas/screen. </h1> 
</br> </br>
<script type="text/javascript" src="//code.createjs.com/createjs-2013.09.25.combined.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#gameCanvas {
  background-color: LightCyan;
}
</style>
<div class="canvasHolder1">

  <div id="alien"> |- - - - -| (1.5 mph)</div>
  <div id="alien1"> </div>
  <div id="alien2">  </div>
  <div id="alien3"></div>
  <div id="alien4">  </div>
<script>
</script>
<canvas id="gameCanvas" width="300" height="300">Not supported</canvas>
<script type="text/javascript">

  var stage = new createjs.Stage("gameCanvas");
  //Trying to create a div array here with id's q0, q1, q2, ..., q3 k is number of numbers
   var k=10;
   var div = [];
   for(i=0; i<=k; i++){
   div[i] = document.createElement('div');
   div[i].id = `q${i}`;
   div[i].style.position = "relative";
   div[i].innerHTML = i;
   div[i].style.top = 0;
   div[i].style.left = 0;
   document.body.appendChild(div[i]);
   }
     //Creating an object array of div elements to add to the stage
  var objectArray = [];
  for(j=0; j<=k; j++){
  objectArray[j] = new createjs.DOMElement(document.getElementById(`q${j}`));
  }
   var object = new createjs.DOMElement(document.getElementById("alien"));
   var object1 = new createjs.DOMElement(document.getElementById("alien1"));
  var object2 = new createjs.DOMElement(document.getElementById("alien2"));
   var object3 = new createjs.DOMElement(document.getElementById("alien3"));
  var object4 = new createjs.DOMElement(document.getElementById("alien4"));
  can = document.getElementById("gameCanvas");
  for(l=0; l<=k; l++){
  objectArray[l].x= 50;
  objectArray[l].y = can.height/10*l;
  }
  object1.x = can.width/3;
  object1.y = 1;
  object2.x = can.width/5;
  object2.y = 1;
  object3.x = can.width/10;
  object3.y = 1;
  object4.x = can.width/2.5;
  object4.y = 1;
  object.x = can.width/2;
  object.y = 1;
  var speedY=5;
  var speedX=5;
  var speedY1=5;
  var speedX1=5;
  var speedY2=5;
  var speedX2=5;
  var speedY3=5;
  var speedX3=5;
  var speedY4=5;
  var speedX4=5;
  var line = new createjs.Shape();
   stage.addChild(line);
   line.graphics.setStrokeStyle(3).beginStroke("rgba(0,0,0,9)");
   line.graphics.moveTo(30, 0);
   line.graphics.lineTo(35, 0);
   line.graphics.lineTo(30, 0);
   for( let n=0; n<=k; n++){
   var j=5;
   line.graphics.lineTo(30, can.height/10*n);
   line.graphics.lineTo(30+j, can.height/10*n);
   line.graphics.lineTo(30, can.height/10*n);
  }
   line.graphics.endStroke();

        function startGame() {
            stage.addChild(object);
            stage.addChild(object1);
            stage.addChild(object2);
            stage.addChild(object3);
            stage.addChild(object4);
            for(i=0; i<=k; i++){
            stage.addChild(objectArray[i]);
            }
           
            createjs.Ticker.addEventListener("tick", handleTick);
              function handleTick(event) {
              drop();
              bottom();
              right();
              left();
              drop1();
              bottom1();
              right1();
              left1();
              drop2();
              bottom2();
              right2();
              left2();
              drop3();
              bottom3();
              right3();
              left3();
              drop4();
              bottom4();
              right4();
              left4();
              
              stage.update();
            }
        }

  function drop(){
  if ( object.y>=can.height|| speedY==5|| object.y<=0){
      object.x += 0;
      object.y +=1;
      speedY=5;
   }
 }
  function bottom(){
   if (object.y>=can.height|| speedY==-5){  // <----- here
     speedY=5;
     object.y =0.5;
     object.x +=0.5;
     document.getElementById("object").textContent = "3k";
   }
 }
 
   function right(){
   if (object.x>=can.width ||speedY==10  ){  // <----- here
     speedY=10;
     object.y -=1;
     object.x -=1;
   }
 }
 function left(){
   if (0>=object.x ||speedY==30  ){  // <----- here
     speedY=30;
     object.y -=0.5;
     object.x +=0.5;
   }
 }
  function drop1(){
  if ( object1.y>=can.height|| speedY1==5|| object1.y<=0){
      object1.x -= 0.5;
      object1.y +=2;
      speedY1=5;
   }
 }
  function bottom1(){
   if (object1.y>=can.height|| speedY1==-5){  // <----- here
     speedY1=-5;
     object1.y -=2;
     object1.x -=0.5;
   }
 }
 
   function right1(){
   if (object1.x>=can.width ||speedY1==10  ){  // <----- here
     speedY1=10;
     object1.y -=1;
     object1.x -=1.5;
   }
 }
 function left1(){
   if (0>=object1.x ||speedY1==30  ){  // <----- here
     speedY1=30;
     object1.y -=1.5;
     object1.x +=1;
   }
 }
  function drop2(){
  if ( object2.y>=can.height|| speedY2==5|| object2.y<=0){
      object2.x += 0;
      object2.y +=1;
      speedY2=5;
   }
 }
  function bottom2(){
   if (object2.y>=can.height|| speedY2==-5){  // <----- here
     speedY2=-5;
     object2.y -=1;
     object2.x +=5;
   }
 }
 
   function right2(){
   if (object2.x>=can.width ||speedY2==10  ){  // <----- here
     speedY2=10;
     object2.y -=6;
     object2.x -=5;
   }
 }
 function left2(){
   if (0>=object2.x ||speedY2==30  ){  // <----- here
     speedY2=30;
     object2.y -=6;
     object2.x +=5;
   }
 }
  function drop3(){
  if ( object3.y>=can.height|| speedY3==5|| object3.y<=0){
      object3.x += 0.5;
      object3.y +=0.2;
      speedY3=5;
   }
 }
  function bottom3(){
   if (object3.y>=can.height|| speedY3==-5){  // <----- here
     speedY3=-5;
     object3.y -=4;
     object3.x -=2;
   }
 }
   function right3(){
   if (object3.x>=can.width ||speedY3==10  ){  // <----- here
     speedY3=10;
     object3.y -=0.5;
     object3.x -=0.5;
   }
 }
 function left3(){
   if (0>=object3.x ||speedY3==30  ){  // <----- here
     speedY3=30;
     object3.y -=0.5;
     object3.x +=0.5;
   }
 }
  function drop4(){
  if ( object4.y>=can.height|| speedY4==5|| object4.y<=0){
      object4.x += 0;
      object4.y +=0.25;
      speedY4=5;
   }
 }
  function bottom4(){
   if (object4.y>=can.height|| speedY4==-5){  // <----- here
     speedY4=-5;
     object4.y -=0.3;
     object4.x +=1;
   }
 }
   function right4(){
   if (object4.x>=can.width ||speedY4==10  ){  // <----- here
     speedY4=10;
     object4.y -=0.5;
     object4.x -=1;
   }
 }
 function left4(){
   if (0>=object4.x ||speedY4==30  ){  // <----- here
     speedY4=30;
     object4.y -=0.5;
     object4.x +=1;
   }
 }
</script>
<body onload="startGame();">
    <div >
  <canvas>This browser or document mode doesn't support canvas object.</canvas>
    </div>
</body>
William Garske
  • 317
  • 1
  • 10
  • 1
    It seems really closely related to this example here but it doesn't seem to work: https://stackoverflow.com/questions/24085445/how-can-i-add-html-dom-element-on-canvas-using-create-js – William Garske Feb 06 '22 at 20:08
  • 1
    I'm confused by what you are trying to achieve. Could you explain what's the goal here? While `handleTick` runs, your code doesn't seem to be updating anything. divs are created (bottom of screen), but don't seem to be used for anything. Also, you are using a 2013 version here, latest stable here `https://code.createjs.com/1.0.0/createjs.min.js` – savageGoat Feb 06 '22 at 20:27
  • 1
    @savageGoat I will the most recent version for now on; thank you for that. I am trying to get the text to appear on the screen part and not below. Does that make sense? – William Garske Feb 07 '22 at 00:05
  • Are you using the canvas for anything else? DOMElements are handy to add HTML content in addition to Canvas content, but if you just are moving DOMElements around, then there are much better solutions, like https://greensock.com/gsap/ – Lanny Feb 07 '22 at 01:09
  • 1
    @william-garske it does make sense, but it doesn't say when, why or how. Are you trying to create a UI for that canvas? Make the text follow the boat? Something else? – savageGoat Feb 07 '22 at 01:43
  • @savageGoat I was able to almost answer it. The issue now is how the pixel number is called onto the screen (it needs to be in the upper left). I can post what I have so far – William Garske Feb 07 '22 at 01:56
  • @william-garske ok, I'm going to go ahead and post what I think you mean then. There's a bunch of functions, methods and other useful things I'm sure you will use. The text follows the ship, the ship moves, there's also a function to display the cursor's coordinates when you move the cursor over it – savageGoat Feb 07 '22 at 02:31

1 Answers1

2

Does this work for you?

<html>
    <script type="text/javascript" src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        body { margin: 0; }
        #gameCanvas { background-color: lightblue; }
        .canvasHolder1 { position: relative; }
        .ui { position: absolute; top: 0; left: 0;  pointer-events: none;}
        .ui-element { position: relative; display: inline-block; margin-left: 4px; }
    </style>
    <body onload="startGame();">
        <div class="canvasHolder1">
            <div id="ship">⛵ </div>
            <div class="ui"></div>
            <canvas id="gameCanvas" width="300" height="300">Not supported</canvas>
        </div>

        <script type="text/javascript">
            const stage = new createjs.Stage("gameCanvas");
            const ship = document.getElementById("ship");
            const ui = document.querySelector(".ui");
            const canvas = document.getElementById("gameCanvas");
            const canvasHolder = document.querySelector('.canvasHolder1');

            var divs = [];
            const texts = [ 'My Ship', 'Pos X', 'Pos Y', 'Other' ];

            for (i = 0; i <= 3; i++) {
                const newDiv = document.createElement("type");
                newDiv.id = `q${i}`;
                newDiv.className = `ui-element`;
                newDiv.innerHTML = texts[i];
                ui.appendChild(newDiv);
                divs.push(newDiv);
            }


            const textXPosition = divs[1];
            const textYPosition = divs[2];
            const textProgress = divs[3];

            canvas.addEventListener('mousemove', (evt) => {
                textXPosition.innerHTML = evt.pageX;
                textYPosition.innerHTML = evt.pageY;
            });


            var objectArray = [];
            objectArray.push(new createjs.DOMElement(divs[0]));
            const myFirstText = objectArray[0];
            const myFirstTextWidth = parseInt(myFirstText.htmlElement.offsetWidth);

            var shipJS = new createjs.DOMElement(ship);

            function applyPosition(posObject) {
                shipJS.x = posObject.x;
                shipJS.y = posObject.y;

                myFirstText.x = posObject.x - (myFirstTextWidth / 2);
                myFirstText.y = posObject.y - 15;
            }

            const shipPosition = {
                x: canvas.width / 3,
                y: 50
            };
            applyPosition(shipPosition);


            let looperCount = -1;
            const step = 0.02;
            const distance = canvas.width / 3;

            function handleTick(event) {
                if (looperCount >= 1) { looperCount = -1; }
                looperCount += step;
                const progress = Math.PI * looperCount;
                textProgress.innerHTML = parseInt(((looperCount + 1) / 2) * 100 )+'%';

                applyPosition({
                    x: (Math.cos(progress) * distance) + (distance * 1.5),
                    y: (Math.sin(progress) * distance) + (distance * 1.5)
                });
                stage.update();
            }


            function startGame() {
                stage.addChild(shipJS);
                stage.addChild(myFirstText);

                createjs.Ticker.addEventListener("tick", handleTick);

            }
        </script>
    </body>
</html>
savageGoat
  • 1,389
  • 1
  • 3
  • 10
  • 1
    @william-garske Glad to help. Be sure to break this code, tear it appart and try your own way to understand how it works. If anything happens, you can still come back here and copy/paste again the clean code – savageGoat Feb 07 '22 at 14:24