Graphic JavaScript

Back to index


As projects get more complicated both the DESIGN and the CODING phases of the software development cycle become more difficult and consequently they take more time and effort. There many coding tricks which programmers use to help them write better code without wasting a lot of time. One of these techniques is creating functions. The student may elect to ignore what follows, but sooner or later the student will need to learn how to create and use methods. It will take a little time now, but it will save a lot of time later!

The following function can be placed in a script and called repeatedly:

  function ast(var x, var y){
    ctx.beginPath();
    ctx.moveTo(x-10,y);
    ctx.lineTo(x+10,y);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(x,y-10);
    ctx.lineTo(x,y+10);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(x+7,y+7);
    ctx.lineTo(x-7,y-7);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(x+7,y-7);
    ctx.lineTo(x-7,y+7);
    ctx.stroke();
  }
This method can then be called REPEATEDLY within the paint method to create as many asterisks as the student desires. Here are three sample calls to the ast method:
  ast(100, 20);
  ast(85, 50);
  ast(115, 50);

EXAMPLE:
Only six asterisks are shown in this example. Inspect the code to see how the applet works. Make sure you understand how the function is called and how it produces the little asterisks.


ASSIGNMENT:
Basically, the student will draw a stack of fifteen triangles arranged with five in the bottom row, four in the next row up, etc.


Your browser does not support the HTML5 canvas tag.