tav-ui
Version:
100 lines (97 loc) • 2.88 kB
JavaScript
import { ref, shallowRef, unref, getCurrentInstance, onBeforeUnmount } from 'vue';
import { useRafThrottle } from '../../utils/domUtils2.mjs';
import { removeResizeListener, addResizeListener } from '../../utils/event/index2.mjs';
import { isDef } from '../../utils/is2.mjs';
const domSymbol = Symbol("watermark-dom");
const DEFAULT_FILL_STYLE = "rgba(0, 0, 0, 0.1)";
const DEFAULT_WATER_MARKER_SIZE = {
width: 300,
height: 240
};
function useWatermark({
appendEl = ref(document.body),
color = DEFAULT_FILL_STYLE,
size = DEFAULT_WATER_MARKER_SIZE
}) {
const id = domSymbol.toString();
const watermarkEl = shallowRef();
const func = useRafThrottle(() => {
const el = unref(appendEl);
if (!el)
return;
const { clientHeight: height, clientWidth: width } = el;
updateWatermark({ height, width });
});
const clear = () => {
const domId = unref(watermarkEl);
watermarkEl.value = void 0;
const el = unref(appendEl);
if (!el)
return;
domId && el.removeChild(domId);
removeResizeListener(el, func);
};
function createBase64(str) {
const can = document.createElement("canvas");
const { width, height } = size;
Object.assign(can, { width, height });
const cans = can.getContext("2d");
if (cans) {
cans.rotate(-20 * Math.PI / 120);
cans.font = "15px Vedana";
cans.fillStyle = color || "rgba(0, 0, 0, 0.1)";
cans.textAlign = "left";
cans.textBaseline = "middle";
cans.fillText(str, width / 20, height);
}
return can.toDataURL("image/png");
}
function updateWatermark(options = {}) {
const el = unref(watermarkEl);
if (!el)
return;
if (isDef(options.width)) {
el.style.width = `100%`;
}
if (isDef(options.height)) {
el.style.height = `100%`;
}
if (isDef(options.str)) {
el.style.background = `url(${createBase64(options.str)}) left top repeat`;
}
}
const createWatermark = (str) => {
if (unref(watermarkEl)) {
updateWatermark({ str });
return id;
}
const div = document.createElement("div");
watermarkEl.value = div;
div.id = id;
div.style.pointerEvents = "none";
div.style.top = "0px";
div.style.left = "0px";
div.style.position = "absolute";
div.style.zIndex = "100000";
const el = unref(appendEl);
if (!el)
return id;
const { clientHeight: height, clientWidth: width } = el;
updateWatermark({ str, width, height });
el.appendChild(div);
return id;
};
function setWatermark(str) {
createWatermark(str);
addResizeListener(document.documentElement, func);
const instance = getCurrentInstance();
if (instance) {
onBeforeUnmount(() => {
clear();
});
}
}
return { setWatermark, clear };
}
export { useWatermark };
//# sourceMappingURL=useWatermark2.mjs.map