Displays a base image and an "x-ray" view of a second image where the mouse is pointing
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

93 行
2.4 KiB

  1. let overlayLoaded = false;
  2. let baseLoaded = false;
  3. let radius = 200;
  4. document.addEventListener("DOMContentLoaded", e => {
  5. const overlayImg = document.querySelector("#overlay-img");
  6. const baseImg = document.querySelector("#base-img");
  7. overlayImg.addEventListener("load", e => {
  8. console.log("The overlay is loaded");
  9. overlayLoaded = true;
  10. if (overlayLoaded && baseLoaded) {
  11. setup();
  12. }
  13. })
  14. baseImg.addEventListener("load", e => {
  15. console.log("The base is loaded");
  16. baseLoaded = true;
  17. if (overlayLoaded && baseLoaded) {
  18. setup();
  19. }
  20. })
  21. });
  22. function setup() {
  23. const overlay = document.querySelector("#overlay");
  24. const base = document.querySelector("#base");
  25. const overlayImg = document.querySelector("#overlay-img");
  26. const baseImg = document.querySelector("#base-img");
  27. /** @type {CanvasRenderingContext2D} */
  28. const overlayCtx = overlay.getContext("2d");
  29. /** @type {CanvasRenderingContext2D} */
  30. const baseCtx = base.getContext("2d");
  31. baseCtx.canvas.width = baseImg.width;
  32. baseCtx.canvas.height = baseImg.height;
  33. baseCtx.drawImage(baseImg, 0, 0);
  34. overlayCtx.canvas.width = overlayImg.width;
  35. overlayCtx.canvas.height = overlayImg.height;
  36. overlayCtx.drawImage(overlayImg, 0, 0);
  37. overlay.addEventListener("mousemove", e => {
  38. let x = e.clientX - e.target.getBoundingClientRect().x;
  39. let y = e.clientY - e.target.getBoundingClientRect().y;
  40. updateOverlay(x, y);
  41. });
  42. console.log("Done");
  43. }
  44. function updateOverlay(x, y) {
  45. console.log("MOVE")
  46. /** @type {CanvasRenderingContext2D} */
  47. const overlayCtx = overlay.getContext("2d");
  48. const overlayImg = document.querySelector("#overlay-img");
  49. const w = overlayCtx.canvas.width;
  50. const h = overlayCtx.canvas.height;
  51. overlayCtx.save();
  52. overlayCtx.globalCompositeOperation = "source-over";
  53. overlayCtx.clearRect(0, 0, w, h);
  54. overlayCtx.beginPath();
  55. overlayCtx.ellipse(x, y, radius, radius, 0, 0, 2 * Math.PI);
  56. const gradient = overlayCtx.createRadialGradient(x, y, 0, x, y, radius);
  57. gradient.addColorStop(0.75, '#000000FF');
  58. gradient.addColorStop(1, '#00000000');
  59. overlayCtx.fillStyle = gradient;
  60. overlayCtx.fill();
  61. overlayCtx.globalCompositeOperation = "source-in";
  62. overlayCtx.drawImage(overlayImg, 0, 0);
  63. overlayCtx.restore();
  64. }