Skip to content

Instantly share code, notes, and snippets.

@benfoxall
Created June 10, 2017 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benfoxall/e7b70dcecd6e8ca1e84fcdc469562574 to your computer and use it in GitHub Desktop.
Save benfoxall/e7b70dcecd6e8ca1e84fcdc469562574 to your computer and use it in GitHub Desktop.
// 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()
}
@benfoxall
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment