我们可以在JavaScript的自定义函数中使用预定义函数吗?

 //making custom function for a fish
 drawFish=function  (centerX,centerY){
 //using draw function for animation
 draw=function(){
 var bodyLength = 115;
 var bodyHeight = 74;
 var bodyColor = color(162, 0, 255);

 noStroke();

 fill(bodyColor);

  // body
 ellipse(centerX, centerY, bodyLength, bodyHeight);

 // tail

 var tailWidth = bodyLength/4;

 var tailHeight = bodyHeight/2;

 triangle(centerX-bodyLength/2, centerY,

 centerX-bodyLength/2-tailWidth, centerY-tailHeight,

 centerX-bodyLength/2-tailWidth, centerY+tailHeight);

 // eye

 fill(33, 33, 33);

 ellipse(centerX+bodyLength/4, centerY, bodyHeight/5, bodyHeight/5);

 centerX++;

 };


 };     
 //calling custom function
 drawFish(146,208);
 drawFish(207,212);
 drawFish(305,306);
 drawFish(114,309);
 drawFish(300,100);

I am trying to make a simple animation of 5 fishes in a tank moving horizontally. I wrote the code for one fish and then I make it a custom function so I can call it as many times as I want. Then I put the draw =function(){} for animation to move the fishes. This code works until I put the draw() function into it otherwise only one fish remains and others disappear. How can we use the draw function to make an animation inside this custom function so that it works on every fish.

评论
静止oo
静止oo

You can try using the operator new. I am not entirely sure if it will work in the way you coded it, but you can do something like:

function drawFish(centerX, centerY) {
   this.centerX = centerX;
   this.centerY = centerY;
   // draw your fish here using centerX and centerY as it's X and Y
}
var fish  = new drawFish(0,0);
var fish1 = new drawFish(50,50);


function Loop() { 
  fish.centerX++ ; fish.centerY++ ;
  fish1.centerX++; fish1.centerY++;
  console.log('Fish position:', fish.centerX, fish.centerY)
  console.log('Fish1 position:',fish1.centerX, fish1.centerY);
}

setInterval(Loop, 500)
点赞
评论