previous

page 18

next
fd()
function fd(t,d) {
g_ctx.strokeStyle=t.colr;
g_ctx.lineWidth=t.width;
g_ctx.beginPath();
g_ctx.moveTo(t.x*g_step,t.y*g_step);
var rad=t.h*Math.PI/180.0;
var dx=d*Math.sin(rad);
var dy=-d*Math.cos(rad);
t.x=t.x+dx; t.y=t.y+dy;
if (t.pen=='down') {
g_ctx.lineTo(t.x*g_step,t.y*g_step);
} else {
g_ctx.moveTo(t.x*g_step,t.y*g_step);
}
g_ctx.stroke();
}

Note that we no longer need all those globals: g_x, g_y, g_h and g_pen.

Let's add a test() function to our index.html and then let's try drawing a square.

function test() {
var t=turtle();
for (var i=0; i<4; i++) {
fd(t,300); rt(t,90);
}
}

Mine worked - did yours? If not, you now have the behind-the-scenes stuff to help you find the problem.

previous
next