Pixel.js 2.8 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. if (canvas.element === document.activeElement) {
  31. canvas.isDragging = true;
  32. }
  33. };
  34. const mouseUp = function(e) {
  35. canvas.isDragging = false;
  36. };
  37. const init = function() {
  38. canvas = {
  39. element: document.getElementById("canvas"),
  40. get context() { return canvas.element.getContext("2d"); },
  41. isDragging: false,
  42. mouse: {
  43. // isInside: false,
  44. x: 0,
  45. y: 0
  46. },
  47. // get boundary() { return canvas.element.getBoundingClientRect(); },
  48. // vertex: {
  49. // get a() { return { x: canvas.boundary.top + window.scrollY, y: canvas.boundary.left + window.scrollX }; },
  50. // get b() { return { x: canvas.boundary.top + window.scrollY, y: canvas.boundary.right }; },
  51. // get c() { return { x: canvas.boundary.bottom, y: canvas.boundary.right }; },
  52. // get d() { return { x: canvas.boundary.bottom, y: canvas.boundary.left + window.scrollX }; }
  53. // }
  54. };
  55. canvas.element.setAttribute("width", 500); // window.getComputedStyle(document.body).getPropertyValue("width"));
  56. canvas.element.setAttribute("height", 500); // window.getComputedStyle(document.body).getPropertyValue("height"));
  57. document.addEventListener("mousemove", mouseMove);
  58. document.addEventListener("mouseup", mouseUp);
  59. document.addEventListener("mousedown", mouseDown);
  60. };