JSFiddle - React, Tailwind, and code Playground
by Roman Zhak
HTML
<canvas width="500px" height="300px" id="ctx"></canvas>
CSS
canvas {
border: 1px solid #999;
}
JavaScript
function createById( id ) {
var el = document.getElementById( id );
var ctx = el.getContext('2d');
return {
el : el,
context : ctx
}
};
function $Canvas( id ) {
this.canvas = createById( id || "ctx")
this.context = this.canvas.context;
this.radius = 3;
this.objects = {
points : []
};
this.width = this.canvas.el.width
this.height = this.canvas.el.height
};
$Canvas.prototype.addPoint = function( x, y ) {
this.objects.points.push({
x : x,
y : this.height - y,
data: new Circle( this.context, x, y, this.radius )
})
};
$Canvas.prototype.joinPoints = function() {
var points = this.objects.points
, start = points.shift();
this.context.beginPath();
this.context.moveTo(start.x, start.y);
for( var i = 0, l = points.length;i < l;i++ ) {
this.context.lineTo(points[i].x, points[i].y);
this.context.stroke();
};
}
$Canvas.prototype.random = function( axis ) {
return $$rand(0, (axis ? this.height : this.width));
}
// test points
var cv = new $Canvas();
var rand = [];
for( var i = 0; i < 50; i++ )
cv.addPoint( i * 10, Math.pow(i,3) / i );
cv.joinPoints();
// circle
function Circle( ctx, x, y, r ) {
ctx.beginPath();
ctx.arc(x, 300 - y, r, 0, 2 * Math.PI);
ctx.lineWidth = 2;
ctx.fillStyle = "blue";
ctx.strokeStyle = "red";
ctx.fill();
ctx.stroke()
}
function $$rand(min, max) {
return Math.random() * (max - min + 1) + min;
}