绘图仪对象
创建绘图仪对象
实例
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> |