Controlling a variable font with mouse movement

271 Views Asked by At

I'm trying to use a variable font whose weight responds to mouse movement. I grabbed some code from a site where this is demonstrated but I can't get it to work. I've made a up a codepen for it. If anyone can spot what's going wrong I'd love to hear it. Thanks

https://codepen.io/mrjonoces/pen/GRmGWpx

h1 = document.getElementById("post_title")
  
function updateText(e) {
  multiplierWidth = e.offsetX / window.innerWidth;
  randomWeight =  multiplierWidth * (700 - 100) + 100;
  h1.fontVariationSettings = "\"wght\" " + randomWeight;
}

window.addEventListener("mousemove", updateText)
2

There are 2 best solutions below

0
On

You need to make sure you're actually loading the variable font.

https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap

will load only the regular single font-weight.

Besides, google might return variable @font-face rules to some browsers.

Open a google font css url like https://fonts.googleapis.com/css2?family=Roboto+Mono:[email protected] ("100..700" will work as a range selection query) for instance in firefox. The result would be:

@font-face {
  font-family: 'Roboto Mono';
  font-style: normal;
  font-weight: 100 700;
  src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhLq38.woff2) format('woff2');} 

The 2 font weight values font-weight: 100 700 indicate we got the variable font.

Example snippet

let h1 = document.getElementById("post_title");
let bb = h1.getBoundingClientRect();
let [x, y, width, height, right] = [
  bb.x,
  bb.y,
  bb.width,
  bb.height,
  bb.width + bb.x
];

function updateText(e) {
  let step = Math.abs(Math.ceil((6 / width) * e.offsetX));
  let newWeight = 100 + 100 * step;
  h1.setAttribute("style", `font-variation-settings: "wght" ${newWeight}`);
  //console.log(newWeight);
}

h1.addEventListener("mousemove", updateText);

let range = document.querySelector('#range')
range.addEventListener("change", function(e) {
  let wght = e.currentTarget.value;
  h1.setAttribute("style", `font-variation-settings: "wght" ${wght}`);
});
@font-face {
  font-family: 'Roboto Mono';
  font-style: normal;
  font-weight: 100 700;
  src: url(https://fonts.gstatic.com/s/robotomono/v22/L0x5DF4xlVMF-BfR8bXMIjhLq38.woff2) format('woff2');
}

h1 {
  font-family: 'Roboto Mono', monospace;
  font-size: 5rem;
  font-weight: 100;
  display: inline-block;
  border: 1px solid red;
  transition: 0.5s;
}
<h1 id="post_title">TITLE</h1>
<p><label for="">Font weight</label>
  <input id="range" type="range" value="100" step="100" min="100" max="700"></p>

0
On

You can check the example codepens at this repo, one of them uses variable fonts: https://github.com/adriano-tirloni/google-fonts-css2