Artificial Intelligence
Plotter Object
Having a Plotter Object is nice when studying Artificial Intelligence:
- Makes AI more Fun
- Makes AI more Visual
- Makes AI more Understandable
Create a Plotter Object
Example
function XYPlotter(id) {
this.canvas = document.getElementById(id);
this.ctx = this.canvas.getContext("2d");
this.xMin = 0;
this.yMin = 0;
this.xMax = this.canvas.width;
this.yMax = this.canvas.height;
.
.
Add a Method for Plotting a Line
Example
this.plotLine = function(x0, y0, x, y, color) {
this.ctx.moveTo(x0, y0);
this.ctx.lineTo(x, y);
this.ctx.strokeStyle = color;
this.ctx.stroke();
}
Add a Method for Transforming XY Values
Example
this.transformXY = function() {
this.ctx.transform(1, 0, 0, -1, 0, this.canvas.height)
}
Add a Method for Plotting Points
Example
this.plotPoints = function(n, xArr, yArr, color, radius = 3) {
for (let i = 0; i < n; i++) {
this.ctx.fillStyle = color;
this.ctx.beginPath();
this.ctx.ellipse(xArr[i], yArr[i], radius, radius, 0, 0, Math.PI * 2);
this.ctx.fill();
}
}
Plot Some Random Points
Example
// Create a Plotter
let myPlotter = new XYPlotter("myCanvas");
// Create Random Points
numPoints = 500;
let xPoints = [];
let yPoints = [];
for (let i = 0; i < numPoints; i++) {
xPoints[i] = Math.random() * myPlotter.xMax;
yPoints[i] = Math.random() * myPlotter.yMax;
}
// Plot the Points
myPlotter.plotPoints(numPoints, xPoints, yPoints, "blue");
Put the Code in a Library
Source Code
function XYPlotter(id) {
this.canvas = document.getElementById(id);
this.ctx = this.canvas.getContext("2d");
this.xMin = 0;
this.yMin = 0;
this.xMax = this.canvas.width;
this.yMax = this.canvas.height;
// Plot Line Function
this.plotLine = function(x0, y0, x, y, color) {
this.ctx.moveTo(x0, y0);
this.ctx.lineTo(x, y);
this.ctx.strokeStyle = color;
this.ctx.stroke();
}
// Transform XY Function
this.transformXY = function() {
this.ctx.transform(1, 0, 0, -1, 0, this.canvas.height)
}
// Pot Points Function
this.plotPoints = function(n, xArr, yArr, color, radius = 3) {
for (let i = 0; i < n; i++) {
this.ctx.fillStyle = color;
this.ctx.beginPath();
this.ctx.ellipse(xArr[i], yArr[i], radius, radius, 0, 0, Math.PI * 2);
this.ctx.fill();
}
}
} // End Plotter Object
Save it in a file (like "myplotlib.js")
Use it in Your HTML Pages
Now you can add your plotter object to your HTML pages:
<script src="myplotlib.js"></script>