Facebook
From DK, 6 Years ago, written in JavaScript.
Embed
Download Paste or View Raw
Hits: 350
  1.  
  2. <style> body { background-color:#ccc; } </style>
  3. <script src="//cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.7/p5.js"></script>
  4. <script type="text/javascript">
  5. function setup() {
  6.     createCanvas(512,512);
  7.     background(255);
  8. }
  9.  
  10. var x0=-1;
  11. var y0=-1;
  12. var x1=-1;
  13. var y1=-1;
  14. var dx,dy,a,b,y=-1,x;
  15. function mousePressed() {
  16.     x0=mouseX;
  17.     y0=mouseY;
  18. }
  19. function mouseDragged() {  
  20.     x1=mouseX;
  21.     y1=mouseY;  
  22.     background(255);
  23.     noStroke();
  24.     fill('red');
  25.     ellipse(x0-3,y0-3,6);
  26.     fill('green');  
  27.     ellipse(x1-3,y1-3,6);
  28. }
  29. function mouseReleased() {
  30.   background(255);
  31.   loadPixels();
  32.   draw_line();
  33.   updatePixels();
  34. }
  35. function set_pixel(x,y,c) {
  36.     idx=(y*512+x)*4;
  37.     pixels[idx]=c;
  38.     pixels[idx+1]=c;
  39.     pixels[idx+2]=c;
  40.     pixels[idx+3]=255;
  41. }
  42. function draw_line() {  
  43.         dx=x1-x0;
  44.     dy=y1-y0;
  45.     a=dy/dx;
  46.         b=y0-a*x0;
  47.    
  48.             for (var i=x0;i<=x1;i++) {
  49.         y=a*(i)+b;
  50.       set_pixel(Math.round(i),Math.round(y),0);
  51.     }
  52. }
  53. </script>