AllenYuan

draw.js draw

Apr 30th, 2020
503
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $(document).ready(function() {
  2.   const canvas = id("mycanvas");
  3.   console.log(canvas);
  4.   let ctx = canvas.getContext("2d");
  5.   // get context to draw on canvas
  6.   let DIMENSION = 25;
  7.   let WIDTH = canvas.width;
  8.   let HEIGHT = canvas.height;
  9.   let PIXELSIZE = WIDTH / DIMENSION;
  10.   let selectedColor = '#222244';
  11.   // records the drawing on this square
  12.   let filledPixels = {};
  13.  
  14.   ctx.strokeStyle = 'rgba(0,0,0,0.1)';
  15.   for (let i = 0; i < DIMENSION; ++i) {
  16.     x = Math.floor(i * WIDTH / DIMENSION);
  17.     ctx.beginPath();
  18.     ctx.moveTo(x, 0);
  19.     ctx.lineTo(x, HEIGHT);
  20.     ctx.stroke();
  21.  
  22.     y = Math.floor(i * HEIGHT / DIMENSION);
  23.     ctx.beginPath();
  24.     ctx.moveTo(0, y);
  25.     ctx.lineTo(WIDTH, y);
  26.     ctx.stroke();
  27.   }
  28.   const events = ['mousedown', 'mousemove', 'touchmove', 'touchstart'];
  29.   for (let i = 0; i < events.length; i++) {
  30.     canvas.addEventListener(events[i], mouseFill);
  31.   }
  32.   function mouseFill(e) {
  33.     e.preventDefault(); // disabled touch scrolling
  34.  
  35.     const rect = id('mycanvas');
  36.     let offsetX = e.offsetX;
  37.     let offsetY = e.offsetY;
  38.  
  39.     // don't paint if user isn't holding mouse down
  40.     if (e.which != 1) return;
  41.     console.log('mouse event', e);
  42.     console.log('filledpixels', filledPixels);
  43.  
  44.     pixel = [Math.floor(offsetX / PIXELSIZE), Math.floor(offsetY / PIXELSIZE)];
  45.     fillPixel(pixel);
  46.   }
  47.  
  48.   function fillPixel(pixel) {
  49.     let key = `${pixel[0]},${pixel[1]}`;
  50.     filledPixels[key] = selectedColor;
  51.  
  52.     ctx.fillStyle = selectedColor;
  53.     ctx.fillRect(pixel[0] * PIXELSIZE, pixel[1] * PIXELSIZE, PIXELSIZE - 1, PIXELSIZE - 1);
  54.   }
  55.  
  56.   function id(id) {
  57.     return document.getElementById(id);
  58.   }
  59. });
Advertisement
Add Comment
Please, Sign In to add comment