<head> <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script> <script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML"> </script> <script type="text/x-mathjax-config"> MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}}); </script> <link rel="stylesheet" href="http://mirkwood.cs.edinboro.edu/~bennett/style/hw.css"> </head> <body> <h1>Y=MX+B, or X = 1/mY +C</h1> Click twice to draw a line. <p> <canvas id="canvas" width="400" height="400" style="border:1px solid #000000;"></canvas> <p> <script type="text/javascript" src="common.js"></script> <script type="text/javascript" src="medLine.js"></script> <script type="text/javascript"> canvas = document.getElementById("canvas"); ctx = canvas.getContext('2d'); canvas.tabIndex = 0; canvas.addEventListener("click", MyHandler); </script>
"use strict" function OtherLine(x0, y0, x1, y1) { let m = (y0-y1)/(x0-x1); if (m >= -1 && m <= 1) { if (x0 > x1) { let tmp = x0; x0 = x1; x1 = tmp; tmp = y0; y0 = y1; y1 = tmp; } let b = y0 - m*x0; for(let x = x0; x <= x1; x++) { let y = m*x + b; SetPixel(x,y); } } else { if (y0 > y1) { let tmp = x0; x0 = x1; x1 = tmp; tmp = y0; y0 = y1; y1 = tmp; } for(let y = y0; y <= y1; y++) { let x = (y-y0)/m + x0; SetPixel(x,y); } } return; }
"use strict" let x0,y0; let x1, y1; let state = 0; function SetPixel(x, y, color = "black") { x = Math.round(x); y = Math.round(y); ctx.beginPath(); ctx.fillStyle = color; ctx.fillRect(x,y,1,1); ctx.fill() return; } function HorizontalLine(x, y0, y1){ let tmp; if (y0 > y1) { tmp = y1; y1 = y0; y0 = tmp; } for(let y = y0; y <= y1; y++) { SetPixel(x,y); } return; } function VerticalLine(y, x0, x1) { let tmp; if (x0 > x1) { tmp = x1; x1 = x0; x0 = tmp; } for(let x = x0; x <= x1; x++) { SetPixel(x,y); } return; } function Line(x0, y0, x1, y1) { let dx, dy; if (x1 == x0) { HorizontalLine(x0, y0, y1); } else if (y0 == y1) { VerticalLine(y0, x0, x1); } else { OtherLine(x0,y0,x1,y1); } return; } function MyHandler(evnt) { switch(state) { case 0: x0= evnt.offsetX; y0 = evnt.offsetY; state = 1; break; case 1: x1= evnt.offsetX; y1 = evnt.offsetY; state = 0; Line(x0, y0, x1, y1); } return; }