我正在制作一个网页,鱼在后台移动。我有一个名为 Fish 的父类和每种鱼的子类。Fish 类有一个 print 方法,我想引用该类的每个实例常用的变量。我需要动态调整图像的大小,所以我想简单地修改物种的变量并调整物种的每个对象。我的问题是:如何为每个类创建一个变量,该变量可以由该类的每个实例在父类方法中使用?
这是我尝试过的简化版本。当然是行不通的。任何帮助将非常感激。
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas"></canvas>
</body>
<script>
function Fish(fi){
this.myPic = fi;
}
Fish.prototype.print = function(cnv, x, y){
cnv.drawImage(this.myPic,x,y);
};
function clownF(){Fish.call(this, clownF.pic);}
clownF.prototype = Object.create(Fish.prototype);
clownF.prototype.constructor = clownF;
clownF.pic = new Image();
clownF.pic.src = "clownF.png";
clownF.pic.onload = function(){
var c=document.getElementById("myCanvas");
c.width = 500;
c.height = 300;
var ctx=c.getContext("2d");
var f = new clownF();
f.print(ctx,10,10);
var temp = document.createElement('canvas');
temp.width = clownF.pic.width / 2;
temp.height = clownF.pic.height / 2;
var tctx = temp.getContext('2d');
tctx.drawImage(clownF.pic,0,0,temp.width,temp.height)
clownF.pic = temp;
f.print(ctx,100,100);
}
</script>
</html>