Một đối tượng Plotter

Có một đối tượng Plotter là tốt khi nghiên cứu Trí tuệ nhân tạo:

  • Làm cho AI thú vị hơn
  • Làm cho AI trở nên trực quan hơn
  • Giúp AI dễ hiểu hơn

Tạo một đối tượng Plotter

Thí dụ

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;
.
.

Thêm một phương pháp để vẽ một đường thẳng

Thí dụ

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();
}


Thêm một phương pháp để chuyển đổi giá trị XY

Thí dụ

this.transformXY = function() {
  this.ctx.transform(1, 0, 0, -1, 0, this.canvas.height)
}


Thêm một phương pháp để vẽ điểm

Thí dụ

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();
  }
}

Lập một số điểm ngẫu nhiên

Thí dụ

// Create a Plotter
let myPlotter = new XYPlotter("myCanvas");

// Create random XY Points
numPoints = 500;
const xPoints = Array(numPoints).fill(0).map(function(){return Math.random() * myPlotter.xMax});
const yPoints = Array(numPoints).fill(0).map(function(){return Math.random() * myPlotter.yMax});

// Plot the Points
myPlotter.plotPoints(numPoints, xPoints, yPoints, "blue");


Đặt mã vào thư viện

Mã nguồn

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

Lưu nó vào một tệp (như "myplotlib.js")

Sử dụng nó trong các trang HTML của bạn

Bây giờ bạn có thể thêm đối tượng máy vẽ vào các trang HTML của mình:

Thí dụ

<script src="myplotlib.js"></script>