简体   繁体   中英

I am trying to get my triangle “duck bill” to scale with the width of my face, how can I do this?

I am self learning through Kahn Academy and can get the triangle on the body to move around when I change the X and Y axis but it won't scale when I make the ellipse bigger for the body and face (I know the ellipse variables need editing to look more round) the triangle moves all over the face. I tried changing the var BillS to 70/faceW which kind of worked to move around the X point, but it still wasn't quite right. What am I doing wrong?

var bodyX = 221;
var bodyY = 202;
var bodyW = 140;
var faceW = bodyW/2;
var bill = faceW/2;
var billY = bodyY -70;
var billS= (faceW/70);

draw = function() {
    background(207, 254, 255);
    fill(240, 209, 36);
    ellipse(bodyX, bodyY, bodyW, 106); // body?
    ellipse(bodyX, bodyY-70, faceW, 47); // face?
    triangle((bodyX-15)*billS, (billY)*billS, (bodyX + 15)*billS, (billY)*billS, (bodyX)*billS, (billY+20)*billS);
};

http://jsfiddle.net/0w7m3qzj/10/

I added some more variables so it doesn't have magic numbers in the function calls. I ported it off of Khan Academy and moved it to a js fiddle and html canvas.

I think the main issue you were having is the graph transformations were a little funky. I like keeping hard coded values out of the function calls and giving them names.

Comments are your friend. When you figure out what a section is doing, mark it up. Whitespace is helpful, too.

Now that the triangle is all based around the center point and the width and height, it should be easier to scale and manipulate.

  var bodyX = 221;
  var bodyY = 202;
  var bodyW = 140;
  var bodyH = 106;
  
  var faceX = bodyX;
  var faceY = bodyY - 70;
  
  var faceW = bodyW/2;
  var faceH = 47;
  var bill = faceW/2;
  var billY = bodyY -70;
  var billS= (faceW/70);
  
  ellipse(ctx, bodyX, bodyY, bodyW, bodyH); // body?
  ellipse(ctx, faceX, faceY, faceW, faceH); // face?
  bill_center_x = faceX;
  bill_center_y = billY + faceH/4;
  bill_height = faceH/2;
  bill_width = faceW/2;
  /* triangle(ctx, 
  (bodyX-15)*billS, (billY)*billS, 
  (bodyX + 15)*billS, (billY)*billS, 
  (bodyX)*billS, (billY+20)*billS); */
    triangle(ctx,
    bill_center_x - bill_width/2,  // left corner of the triangle
    bill_center_y - bill_height/2,

    bill_center_x,                 // bottom center of the triangle
    bill_center_y + bill_height/2,

    bill_center_x + bill_width/2,  // right side of the triangle
    bill_center_y - bill_height/2
  )

Note when moving this back to Khan Academy, remove the ctx parameter in the triangle and ellipse calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM