我正在构建一个浏览器扩展程序,用于在第三方网站的图像上方绘制内容。为简单起见,假设它在图像中心上方绘制了一个大小为(img.width/2, img.height/2)
的红色框。例如,请参见此图。
我当前正在创建红色的<div>
,并根据从style.width
计算出的值将其设置为style.height
,style.left
,style.top
和<img>
。看来这种方法很脆弱,因为总会有另一种花哨的变换/动画需要我手动处理。例如,我没有考虑下图所示的旋转或偏斜。
是否有办法说我的div
应该继承<img>
的所有转换,所以无论页面开发者做什么,我的内容都会根据它移动?
确定,这花了一点时间,但我自己解决了。
键是一个称为getComputedStyle
的函数,该函数在执行所有操作后返回图像的净CSS变换。您需要正确堆叠非CSS转换。我认为您只能在没有CSS的情况下缩放和转换图像,因此这很简单。
// get the CSS transform and it's origin
const cssProps = window.getComputedStyle(image);
const transformOrigin = cssProps["transformOrigin"]
const transform: cssProps["transform"]
// get the HTML scaling and translation
const left = image.offsetLeft;
const top = image.offsetTop;
const width = image.width;
const height = image.height;
// create a new element and set it's color
const elem = document.createElement('div');
elem.style.zIndex = 10;
elem.style.border = 'solid red 2px';
elem.style.position = 'absolute';
// set the css transform and origin
elem.style.transformOrigin = basePos.transformOrigin;
elem.style.transform = `${basePos["transform"]} translate(${left}px, ${top}px)`;
elem.style.width = `${width/2}px`;
elem.style.height = `${height/2}px`;
此方法的唯一缺点是您必须等待页面完成加载才能使用getComputedStyle
。
所以这对我来说似乎有点过头了。如果您尝试过此操作,则为Idk,但是使包含相对于整个旋转窗口的整个div并执行类似的操作也可以...
html:
<body> <!-- or whatever the parent is of the whole view -->
<div class="overlay-window">
<div class="image-overlay">
</div>
</div>
</body>
scss:
body {
position: relative;
.overlay-window {
bottom: 0;
left: 0;
position: absolute:
right: 0;
top: 0;
.image-overlay {
// add grid styling in the parent of this to position your
// image outline or however you want to position it here
}
}
}
即使只是制作覆盖图,也无需使用javascript东西tbh。这应该避免旋转的需要,因为它实际上将与旋转对象分开。