I am trying to implement two methods. One to jump to a specific coordinates, the other to draw a line from the current position to the given koordinate.
After using the method lineToXY or moveToXY, I cannot use forward anymore. Somehow it always draws in the wrong direction and way further then expected.
class Turtle {
constructor(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.reset();
}
reset() {
this.ctx.reset();
this.x = 0;
this.y = 0;
this.angle = 0;
this.penDown();
this.color("black");
}
resetMoveTo() {
this.penDown();
this.color("black");
}
penDown() {
this.isPenDown = true;
}
penUp() {
this.isPenDown = false;
}
forward(distance) {
const radians = (this.angle * Math.PI) / 180;
const newX = this.x + distance * Math.cos(radians);
const newY = this.y + distance * Math.sin(radians);
if (this.isPenDown) {
this.ctx.beginPath();
this.ctx.moveTo(this.x, this.y);
this.ctx.lineTo(newX, newY);
this.ctx.stroke();
}
this.x = newX;
this.y = newY;
}
backward(distance) {
this.forward(-distance);
}
right(degrees) {
this.angle += degrees;
}
left(degrees) {
this.angle -= degrees;
}
color(color) {
this.ctx.strokeStyle = color;
}
lineWidth(width) {
this.ctx.lineWidth = width;
}
text(text, font = '10px sans-serif', align = 'center') {
const radians = (this.angle * Math.PI) / 180 + Math.PI / 2.0;
this.ctx.save();
this.ctx.translate(this.x, this.y);
this.ctx.rotate(radians);
this.ctx.font = font;
this.ctx.fillStyle = this.ctx.strokeStyle;
this.ctx.textAlign = align;
this.ctx.fillText(text, 0, 0);
this.ctx.restore();
}
moveToXY(x, y) {
this.x = x;
this.y = y;
}
lineToXY(x, y) {
if (this.isPenDown) {
this.ctx.beginPath();
this.ctx.moveTo(this.x, this.y);
this.ctx.lineTo(x, y);
this.ctx.stroke();
}
this.x = x;
this.y = y;
}
}
Example:
jshell> /o lvp.java
jshell> Clerk.view();
Open http://localhost:50001 in your browser
$59 ==> LiveView@69379752
jshell> Turtle t = new Turtle(500,500);
t ==> Turtle@1d7acb34
jshell> t.lineToXY(50,50);
$61 ==> Turtle@1d7acb34
jshell> t.forward(10);
$62 ==> Turtle@1d7acb34
Outcome
It should just draw a line to 50,50 and then go forward for 10. But it draws a very long line with a false angle.
New contributor
XxX is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.