6

In html5 how do i place the class below (constructor and method)in another file and reference it in the html file.

Below I have everything in 1 file and I dont want that.

  <canvas id="myCanvas" width="600" height="400"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext('2d');
  ctx.font="14px Arial"; 



  //how to move to other file
  function ClassPerson(gender,name1) {
      var aa;
      this.gender=gender;
      this.name1=name1;
      aa=6;

  };

   //how to move to other file
  ClassPerson.prototype.m_sayGender = function()
    {
    ctx.fillText("this gender= " + this.gender + " gender=" + this.name1,10,40);
    };

    //stay in this file
  var person1 = new ClassPerson('male','dave');
  var person2 = new ClassPerson('female','bet');
  ctx.fillText("this gender= " + person1.gender,10,20);
  person1.m_sayGender();
  myObject._three();

</script>

2 Answers 2

7

You simply create an external JS file with your code and include it like this:

<script src="myFile.js"> </script> or

<script src="<myFile>.js" type="text/javascript"></script>

Be sure to place the JS file in the directory where you have your HTML file

After comment: I guess you have to dynamically create an image with javacript set it's src porpertie and the diplay it.

Sign up to request clarification or add additional context in comments.

3 Comments

ok that works but why did I get a -1 vote? My example was without an image which is what I wanted to ask. How do I access an image loaded in a class from another file using canvas/html5.
I cant ask another question and paste the code of what I am talking about? I cant get access to the image from a class.
0

Set the whole JS code of your class in an external *.js file. Then import it into your *.html file like this:

<script src="<external-file-name>.js" type="text/javascript"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.