Only the position of the whole TikZ picture is saved to the aux files, the dimensions of nodes are only known after they have been constructed.
Here's an approach where the TikZ picture is constructed only after all nodes have been constructed (and are then known). By adding this TikZ picture to the background shipout hook this will be placed behind the normal text.
Code (shipout)
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{tikzmark}
\NewDocumentEnvironment{tikz-bg}{O{} +b}{%
\AddToHookNext{shipout/background}{%
\put(0,0){%
\begin{tikzpicture}[remember picture,overlay,#1]%
#2%
\end{tikzpicture}}}}{}
\begin{document}
This is some text: \tikzmarknode{Foo}{foo}.
And this is some text in between that the filling partially covers
And this is another node:\tikzmarknode{Bar}{bar}
\begin{tikz-bg}
\fill[red] (Foo.north west) -- (Bar.south west)
-- (Bar.south east) -- (Foo.north east) -- cycle;
\end{tikz-bg}
\end{document}
The tikzmark library has support for saving the node (i.e. its placement inside a TikZ picture and its anchors):
Each node that needs to be known beforehand needs to use save node whereas the nodes TikZ picture needs save nodes to file.
For some reason, everything is shifted downwards, maybe something's not saved correctly or at the corrent point. The commented hack seems to be a workaround for the underlying issue.
Code (saved nodes)
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{tikzmark}
\tikzset{
every tikzmarknode picture/.style=save nodes to file,
restore nodes from file,
save node/.append style={anchor=center}% hack
}
\begin{document}
\tikz[remember picture, overlay]
\fill[red] (Foo.north west) -- (Bar.south west)
-- (Bar.south east) -- (Foo.north east) -- cycle;%
This is some text: \tikzmarknode[save node]{Foo}{foo}.
And this is some text in between that the filling partially covers
And this is another node: \tikzmarknode[save node]{Bar}{bar}
\end{document}
\begin{tikzpicture}[remember picture, overlay,blend mode=multiply]should do the job – samcarter_is_at_topanswers.xyz May 14 '23 at 19:02\tikzmarkinstead of\tikzmarknode. – John Kormylo May 14 '23 at 21:40auxfile which makes it possible to use a node's position before it is defined, but it doesn't do it by default for\tikzmarknodeso you'd have to add the right keys. – Andrew Stacey May 14 '23 at 22:32