Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <body>
- <style>
- body {
- padding: 0;
- margin: 0;
- overflow: hidden;
- }
- </style>
- <canvas id="canvas" width="300" height="300" style="border:1px solid;"></canvas>
- <script>
- function deCasteljau(points, step) {
- let final = new Array();
- let n = points.length;
- for(let t=0; t<=1; t+=step) {
- let dummy = new point(0, 0);
- for(let i=0; i<n; i++) {
- var bp = bernsteinPolynomial(t, n-1, i);
- let transformed = new point(points[i].x, points[i].y).multX(bp).multY(bp);
- dummy.incX(transformed.x).incY(transformed.y);
- }
- final.push(dummy);
- }
- return final;
- }
- function point(x, y) {
- this.x = x;
- this.y = y;
- this.constructor.prototype.incX = function(inc) {
- this.x += inc;
- return this;
- }
- this.constructor.prototype.multX = function(mult) {
- this.x *= mult;
- return this;
- }
- this.constructor.prototype.multY = function(mult) {
- this.y *= mult;
- return this;
- }
- this.constructor.prototype.incY = function(inc) {
- this.y += inc;
- return this;
- }
- }
- function bernsteinPolynomial(t, n, i) {
- if(t == 1) return 0;
- return binomialCoefficient(n, i) * Math.pow(t, i) * Math.pow((1-t), n-i);
- }
- function binomialCoefficient(n, i) {
- let nominator = factorial(n);
- let denominator = factorial(i) * factorial((n-i))
- return (denominator < 0) ? 0 : nominator/denominator;
- }
- function factorial(num) {
- let res = num;
- if(num == 0){return 1};
- while(num >= 2) {
- res *= --num;
- }
- return res;
- }
- function goGraphic(cps) {
- let canvas = document.getElementById("canvas");
- let ctx = canvas.getContext("2d");
- canvas.width = canvas.width;
- ctx.fillStyle = "black";
- ctx.rect(0, 0, canvas.width, canvas.height);
- ctx.fill();
- let points = new Array();
- for(let i=0; i<cps.length; i++) {
- points.push(new point(cps[i][0], cps[i][1]));
- }
- let curve = deCasteljau(points, 0.001);
- ctx.shadowColor = "yellow";
- ctx.strokeStyle = "yellow";
- ctx.shadowOffsetX = 10;
- ctx.shadowOffsetY = 10;
- ctx.shadowBlur = 15;
- for(let i=0; i<curve.length; i++) {
- ctx.lineWidth = 3-i/500;
- ctx.beginPath();
- ctx.moveTo(curve[i].x, curve[i].y);
- if((i+1) < curve.length) {
- ctx.lineTo(curve[i+1].x, curve[i+1].y);
- }
- ctx.stroke();
- ctx.closePath();
- }
- }
- let points = [];
- document.body.onload = function(e) {let canvas = document.getElementById("canvas");canvas.width = screen.width;canvas.height = screen.height;goGraphic([]);}
- document.getElementById("canvas").onclick = function(e) {
- let x = e.pageX - e.target.offsetLeft;
- let y = e.pageY - e.target.offsetTop;
- points.push([x, y]);
- goGraphic(points);
- }
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement