Pixel.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. var canvas;
  2. const draw = function(ctx, source, coords) {
  3. ctx.clearRect(0, 0, canvas.element.width, canvas.element.height);
  4. const img = new Image();
  5. img.onload = function() {
  6. ctx.drawImage(img, coords.x, coords.y);
  7. };
  8. img.src = source;
  9. };
  10. const dotProduct = function(U, V) {
  11. return U.x * V.x + U.y * V.y;
  12. };
  13. const mouseMove = function(e) {
  14. canvas.mouse.x = e.clientX;
  15. canvas.mouse.y = e.clientY;
  16. const AB = { x: canvas.vertex.b.x - canvas.vertex.a.x, y: canvas.vertex.b.y - canvas.vertex.a.y };
  17. const AM = { x: canvas.mouse.x - canvas.vertex.a.x, y: canvas.mouse.y - canvas.vertex.a.y };
  18. const BC = { x: canvas.vertex.c.x - canvas.vertex.b.x, y: canvas.vertex.c.y - canvas.vertex.b.y };
  19. const BM = { x: canvas.mouse.x - canvas.vertex.b.x, y: canvas.mouse.y - canvas.vertex.b.y };
  20. canvas.mouse.isInside = (0 <= dotProduct(AB, AM) && dotProduct(AB, AM) <= dotProduct(AB, AB))
  21. && (0 <= dotProduct(BC, BM) && dotProduct(BC, BM) <= dotProduct(BC, BC));
  22. console.log("Dragging: " + canvas.isDragging);
  23. console.log("Inside: " + canvas.mouse.isInside);
  24. if (canvas.isDragging) {
  25. draw(canvas.context, "https://snippets.cdn.mozilla.net/media/icons/56efef37-8e21-49df-9699-df9ae2c8a088.png", canvas.mouse);
  26. }
  27. };
  28. const mouseDown = function(e) {
  29. if (canvas.mouse.isInside) {
  30. canvas.isDragging = true;
  31. }
  32. };
  33. const mouseUp = function(e) {
  34. canvas.isDragging = false;
  35. };
  36. const init = function() {
  37. canvas = {
  38. element: document.getElementById("canvas"),
  39. get context() { return canvas.element.getContext("2d"); },
  40. isDragging: false,
  41. mouse: {
  42. isInside: false,
  43. x: 0,
  44. y: 0
  45. },
  46. get boundary() { return canvas.element.getBoundingClientRect(); },
  47. vertex: {
  48. get a() { return { x: canvas.boundary.top + window.scrollY, y: canvas.boundary.left + window.scrollX }; },
  49. get b() { return { x: canvas.boundary.top + window.scrollY, y: canvas.boundary.right }; },
  50. get c() { return { x: canvas.boundary.bottom, y: canvas.boundary.right }; },
  51. get d() { return { x: canvas.boundary.bottom, y: canvas.boundary.left + window.scrollX }; }
  52. }
  53. };
  54. canvas.element.setAttribute("width", 500);//window.getComputedStyle(document.body).getPropertyValue("width"));
  55. canvas.element.setAttribute("height", 500);//window.getComputedStyle(document.body).getPropertyValue("height"));
  56. document.addEventListener("mousemove", mouseMove);
  57. document.addEventListener("mouseup", mouseUp);
  58. document.addEventListener("mousedown", mouseDown);
  59. };