Created
June 10, 2017 10:16
-
-
Save benfoxall/e7b70dcecd6e8ca1e84fcdc469562574 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// includes regression | |
// https://unpkg.com/regression@1.4.0/build/regression.min.js | |
var canvas = document.createElement('canvas') | |
var ctx = canvas.getContext('2d') | |
document.body.appendChild(canvas) | |
Object.assign(canvas.style, {border:'1px solid #ccc', margin:0}) | |
var m = 1 | |
var c = 0 | |
var points = [] | |
// calculate m & c from points | |
function doCalculation() { | |
var result = regression('linear', points) | |
m = result.equation[0] | |
c = result.equation[1] | |
} | |
canvas.addEventListener('mouseenter', () => points = []) | |
canvas.addEventListener('mousemove', (e) => { | |
points.push([e.clientX, e.clientY]) | |
doCalculation() | |
draw() | |
}) | |
function draw () { | |
ctx.clearRect(0,0, canvas.width, canvas.height) | |
ctx.beginPath() | |
points.forEach(([x,y]) => { | |
ctx.lineTo(x,y) | |
}) | |
ctx.strokeStyle = '#08f' | |
ctx.stroke() | |
ctx.beginPath() | |
ctx.lineTo(0,c) | |
ctx.lineTo(canvas.width,canvas.width*m + c) | |
ctx.strokeStyle = '#f08' | |
ctx.stroke() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://jsbin.com/qaziqeyamu/edit?js,output