我创建了一个带有海龟图形的 Javascript 程序,我想知道如何在每个绘图的末尾放置一个指向三角形(或任何形状),以便我可以选择绘图的哪一侧。
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>HTML5 canvas turtle graphics</title>
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
canvas {border: 1px dotted #564b47;}
</style>
</head>
<body>
<h1>HTML5 canvas turtle graphics</h1>
<canvas id="myDrawing" width="600" height="300"></canvas>
<script type="text/javascript">
"use strict";
// JavaScript statements
// =====================================================================================
var color = {
black: "#ffffff",
red: "#ff0000",
green: "#00ff00",
blue: "#0000ff",
yellow: "#ffff00",
fuchsia: "#ff00ff",
aqua: "#00ffff"
};
var turtle = {
x: 0,
y: 0,
angleInRadians: 0,
penDown: false,
penColor: "#000000",
lineWidth: 2
};
var canvas = document.getElementById('myDrawing');
if (canvas && canvas.getContext) { // does the browser support 'canvas'?
turtle.ct = canvas.getContext("2d"); // get drawing context
} else {
alert('You need a browser which supports the HTML5 canvas!');
}
// =====================================================================================
turtle.logPenStatus = function () {
console.log('x=' + this.x + "; y=" + this.y + '; angle = ' + this.angle + '; penDown = ' + this.penDown);
};
turtle.forward = function (length) {
// console.log('forward(' + length + ')');
// this.logPenStatus();
var x0 = this.x,
y0 = this.y;
this.x += length * Math.sin(this.angleInRadians);
this.y += length * Math.cos(this.angleInRadians);
if (this.ct) {
if (this.penDown) {
//this.logPenStatus();
this.ct.beginPath();
this.ct.lineWidth = this.lineWidth;
this.ct.strokeStyle = this.penColor;
this.ct.moveTo(x0, y0);
this.ct.lineTo(this.x, this.y);
this.ct.stroke();
}
} else {
this.ct.moveTo(this.x, this.y);
}
return this;
};
turtle.backward = function (length) {
this.forward(-length);
return this;
};
turtle.left = function (angleInDegrees) {
// console.log('left(' + angleInDegrees + ')');
// A complete circle, 360º, is equivalent to 2? radians
// angleInDegrees is an angle measure in degrees
this.angleInRadians += angleInDegrees * Math.PI / 180.0;
return this;
};
turtle.right = function (angleInDegrees) {
this.left(-angleInDegrees);
return this;
};
turtle.angle = function () {
// the turtle status is hold in this.angleInRadians;
// degrees are often more convenient for the display
return this.angleInRadians * 180.0 / Math.PI;
};
例如这里是一个简单的绘图
turtle.x = 50; // the x-axis of the pen
turtle.y = 100; // the y-axis of the pen
turtle.penDown = true;
turtle.forward(50);
turtle.left(150);
turtle.forward(7);
turtle.backward(7);
turtle.right(150);
turtle.right(150);
</script>
</body>
</html>