Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <style>
- #bgr {
- position: absolute;
- left: 10px;
- top: 10px;
- }
- #msk0, #msk1 {
- position: absolute;
- left: 10px;
- top: 10px;
- }
- .visible {
- opacity: 0.5;
- mix-blend-mode: multiply;
- transition: opacity .5s ease-in-out;
- }
- .invisible {
- opacity: 0.0;
- transition: opacity .5s ease-in-out;
- }
- </style>
- </head>
- <body>
- <img id= "bgr" onmousemove="trackMouse(event)" src="img.jpg"/>
- <img id="msk0" onmousemove="trackMouse(event)" class="invisible"/>
- <img id="msk1" onmousemove="trackMouse(event)" class="invisible"/>
- <script>
- lastMask = -1;
- curMaskImg = 0;
- function trackMouse(e) {
- var maskAtMouse = -1;
- for (var i = 0; i < masks.length; i++) {
- var m = masks[i];
- if (pointInsideBox(e.clientX, e.clientY, m.bbox)) {
- var pixel = getMaskPixel(m, e.clientX, e.clientY);
- if (pixel[0] === 255) {
- maskAtMouse = i;
- break;
- }
- }
- }
- if (maskAtMouse != -1 && lastMask != maskAtMouse) {
- lastMask = maskAtMouse;
- document.getElementById("msk" + curMaskImg).classList = "invisible";
- curMaskImg = (curMaskImg + 1) % 2;
- document.getElementById("msk" + curMaskImg).src = masks[maskAtMouse].dataUrl;
- document.getElementById("msk" + curMaskImg).classList = "visible";
- }
- if (maskAtMouse == -1 && lastMask != -1) {
- lastMask = -1;
- document.getElementById("msk0").classList = "invisible";
- document.getElementById("msk1").classList = "invisible";
- }
- }
- function getMaskPixel(mask, x, y) {
- return mask.getContext("2d").getImageData(x, y, 1, 1).data;
- }
- function determineBoundingBox(mask) {
- var ctx = mask.getContext("2d");
- var imgData = ctx.getImageData(0, 0, mask.width, mask.height);
- var minX = mask.width;
- var maxX = -1;
- var minY = mask.height;
- var maxY = -1;
- var idx = 0;
- for (var y = 0; y < mask.height; y++) {
- for (var x = 0; x < mask.width; x++) {
- if (imgData.data[idx] == 255) {
- minX = x < minX ? x : minX;
- minY = y < minY ? y : minY;
- maxX = x > maxX ? x : maxX;
- maxY = y > maxY ? y : maxY;
- }
- idx += 4;
- }
- }
- ctx.putImageData(imgData, 0, 0);
- return {"x1": minX, "y1": minY, "x2": maxX, "y2": maxY};
- }
- function pointInsideBox(x, y, bbox) {
- return !(x < bbox.x1 || x > bbox.x2 || y < bbox.y1 || y > bbox.y2);
- }
- function preProcessMasks(i) {
- var tmpImg = new Image;
- tmpImg.onload = () => {
- var mask = document.createElement("canvas");
- mask.width = tmpImg.width;
- mask.height = tmpImg.height;
- mask.getContext("2d").drawImage(tmpImg, 0, 0, tmpImg.width, tmpImg.height);
- mask.bbox = determineBoundingBox(mask);
- mask.dataUrl = mask.toDataURL("image/png");
- masks.push(mask);
- }
- tmpImg.src = "./" + i + ".jpg";
- }
- </script>
- <script>
- var masks = [];
- for (var i=1; i <= 5; ++i)
- preProcessMasks(i);
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement