LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 304|回复: 0

绘图仪对象

[复制链接]
发表于 2024-1-16 16:18:27 | 显示全部楼层 |阅读模式

绘图仪对象
创建绘图仪对象
实例
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;
.
.
添加绘制线条的方法
实例
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();
}

添加转换 XY 值的方法
实例
this.transformXY = function() {
  this.ctx.transform(1, 0, 0, -1, 0, this.canvas.height)
}

添加绘制点的方法
实例
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, yArr, radius, radius, 0, 0, Math.PI * 2);
    this.ctx.fill();
  }
}
绘制一些随机点
实例
// 创建绘图仪
let myPlotter = new XYPlotter("myCanvas");

// 创建随机 XY 点
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");

将代码放入库中
源代码
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;

// 绘图线函数
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();
}

// 变换 XY 函数
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, yArr, radius, radius, 0, 0, Math.PI * 2);
    this.ctx.fill();
  }
}

} // End Plotter Object
将其保存在文件中(如"myplotlib.js")

在您的 HTML 页面中使用它
现在您可以将绘图仪对象添加到 HTML 页面:

实例
<script src="myplotlib.js"></script>
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表