在 html5 中,我如何将下面的类(构造函数和方法)放在另一个文件中并在 html 文件中引用它。
下面我将所有内容都放在 1 个文件中,但我不想要那个。
<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>
最佳答案
您只需使用您的代码创建一个外部 JS 文件 并像这样包含它:
<script src="myFile.js"> </script>
或
<script src="<myFile>.js" type="text/javascript"></script>
请务必将 JS 文件放在您的 HTML 文件所在的目录中
评论后:我猜你必须使用 javacript 动态创建图像,并将其设置为 src
性能和显示效果。
关于javascript - 将 javascript 放在 html5 的外部文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15896704/