AllenYuan

index.js interactivity

May 1st, 2020
621
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $(document).ready(function () {
  2.   let PIXELSIZE = 2;
  3.   let REPEATSX = 20;
  4.   let REPEATSY = 15;
  5.   let DIMENSION = 25;
  6.  
  7.   let canvas = id('mycanvas');
  8.   let ctx = canvas.getContext("2d");
  9.   let canvasWidth = DIMENSION * REPEATSX * PIXELSIZE;
  10.   let canvasHeight = DIMENSION * REPEATSY * PIXELSIZE;
  11.   let selectedBox = null;
  12.  
  13.   canvas.width = canvasWidth;
  14.   canvas.height = canvasHeight;
  15.  
  16.   // draw grid
  17.   ctx.strokeStyle = '#cccccc';
  18.   for (let i = 0; i < DIMENSION * REPEATSX; i += DIMENSION) {
  19.     x = i * PIXELSIZE;
  20.     ctx.beginPath();
  21.     ctx.moveTo(x, 0);
  22.     ctx.lineTo(x, canvasHeight);
  23.     ctx.stroke();
  24.  
  25.     y = i * PIXELSIZE;
  26.     ctx.beginPath();
  27.     ctx.moveTo(0, y);
  28.     ctx.lineTo(canvasWidth, y);
  29.     ctx.stroke();
  30.   }
  31.  
  32.   canvas.addEventListener('click', selectBox);
  33.   let SELECTED = 0;
  34.   function selectBox(e) {
  35.     if (SELECTED) return;
  36.     SELECTED = 1;
  37.  
  38.     console.log('canvas click', e);
  39.  
  40.     let pixel = [Math.floor(e.offsetX / (PIXELSIZE * DIMENSION)), Math.floor(e.offsetY / (PIXELSIZE * DIMENSION))];
  41.     window.location = `draw.php?x=${pixel[0]}&y=${pixel[1]}`
  42.   }
  43.  
  44.   canvas.addEventListener('mousemove', highlightBox);
  45.   function highlightBox(e) {
  46.     console.log('mousemove', e);
  47.  
  48.     let pixel = [Math.floor(e.offsetX / (PIXELSIZE * DIMENSION)), Math.floor(e.offsetY / (PIXELSIZE * DIMENSION))];
  49.     // boundary conditions
  50.     if (pixel[0] < 0 || pixel[1] < 0 ||
  51.     pixel[0] >= REPEATSX || pixel[1] >= REPEATSY) {
  52.       return;
  53.     }
  54.     // create a translucent selectedBox div where the user moves their mouse
  55.     if (!selectedBox) {
  56.       selectedBox = $("<div id=selectedBox></div>");
  57.       selectedBox.css({ width: DIMENSION * PIXELSIZE - 2, height: DIMENSION * PIXELSIZE - 2 });
  58.       $("#mycanvasWrapper").prepend(selectedBox);
  59.     }
  60.     selectedBox.css({
  61.       left: pixel[0] * PIXELSIZE * DIMENSION + 1,
  62.       top: pixel[1] * PIXELSIZE * DIMENSION
  63.     });
  64.   }
  65.  
  66.   function id(id) {
  67.     return document.getElementById(id);
  68.   }
  69. });
Advertisement
Add Comment
Please, Sign In to add comment