Categories
JavaScript Answers

How to Dynamically Change Font Size Based on Text Length Using JavaScript?

Sometimes, we want to dynamically change font size based on text length using JavaScript.

In this article, we’ll look at how to dynamically change the size of font size based on text length using JavaScript.

Dynamically Change Font Size Based on Text Length Using JavaScript

To dynamically change the size of font size based on text length using JavaScript, we can resize the text if the height of the containing div is bigger than the div containing the text.

For instance, we write:

<input type="text" >

<div id="outer" class="container" style="width:80%; height:100px; border:2px solid red; font-size:20px;">

  <div class="output" style="word-break: break-all; word-wrap: break-word;">
  </div>

</div>

to add the input to enter the text and the outer and inner divs.

The inner div will contain the text.

Next, we write:

const input = document.querySelector('input');
const output = document.querySelector('.output');
const outputContainer = document.querySelector('.container');

const resizeToFfit = () => {
  let fontSize = window.getComputedStyle(output).fontSize;
  output.style.fontSize = (parseFloat(fontSize) - 1) + 'px';

  if (output.clientHeight >= outputContainer.clientHeight) {
    resizeToFfit();
  }
}

function processInput() {
  output.innerHTML = this.value;
  output.style.fontSize = '100px';
  resizeToFfit();
}

input.addEventListener('input', processInput);

to select the elements with document.querySelector.

Then we add the resizeToFit function that gets the font size of the output element with getComputedStyle.

Next, we set the fontSize to the parsed font size with:

output.style.fontSize = (parseFloat(fontSize) - 1) + 'px';

Then if output.clientHeight is bigger than or equal to outputContainer.clientHeight, we call resizeToFit to resize the text.

Then we add the processInput function that takes the input value with this.value and assign it to output.innerHTML to show the text.

Next, we set the font size of the text to 100px.

And finally, we call resizeToFit to make the text fit in the box.

Then we call input.addEventListener to listen to the input event and run processInput when we type in something into the input.

Conclusion

To dynamically change the size of font size based on text length using JavaScript, we can resize the text if the height of the containing div is bigger than the div containing the text.

Categories
JavaScript Answers

How to Trigger CSS Animations in JavaScript?

Sometimes, we want to trigger CSS animations in JavaScript.

In this article, we’ll look at how to trigger CSS animations in JavaScript.

Trigger CSS Animations in JavaScript

To trigger CSS animations in JavaScript, we just add the class that is set to animate the keyframes in CSS.

For instance, if we have:

<div class='TimeCountdown_circle1'>
  circle
</div>
<div class='TimeCountdown_circle2'>
  circle
</div>

Then we add animation with:

@keyframes circle1 {
  from {
    background-color: red;
  }

  to {
    background-color: yellow;
  }
}

@keyframes circle2 {
  from {
    background-color: red;
  }

  to {
    background-color: yellow;
  }
}

.circle_ani1,
.circle_ani2 {
  animation-duration: 1s;
  animation-iteration-count: 1;
}

.circle_ani1 {
  animation-name: circle1;
}

.circle_ani2 {
  animation-name: circle2;
}

We add the @keyframes property with the animation we want to animate.

It’ll animate from the from styles to the to styles.

Then we set the animation-name to the keyframes we want to animate within the class selectors.

Next, we write:

const tempCircle1 = $('.TimeCountdown_circle1').removeClass('circle_ani1');
const tempCircle2 = $('.TimeCountdown_circle2').removeClass('circle_ani2');
window.setTimeout(() => {
  tempCircle1.addClass('circle_ani1');
  tempCircle2.addClass('circle_ani2');
}, 50);

to remove the circle_ani1 and circle_ani2 classes with jQuery’s removeClass after we select them.

Then we call addClass to add the classes to the elements.

Conclusion

To trigger CSS animations in JavaScript, we just add the class that is set to animate the keyframes in CSS.

Categories
JavaScript Answers

How to Set the Scrollbar Position with JavaScript?

Sometimes, we want to set the scrollbar position with JavaScript.

In this article, we’ll look at how to set the scrollbar position with JavaScript.

Set the Scrollbar Position with JavaScript

To set the scrollbar position with JavaScript, we can set the scrollTop property of the scroll container element to the value of the offsetTop property of the element we want to scroll to.

For instance, if we have:

<div id='container' style='height: 100px; overflow-y: scroll'>
  <div>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis augue a ante rutrum, non ornare erat maximus. Fusce sagittis nunc sed tellus sagittis, vitae volutpat odio faucibus. Nullam consequat ut mi a consequat. Praesent a porttitor magna. Donec placerat mollis sapien ac eleifend.
  </div>
  <div id='row'>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis augue a ante rutrum, non ornare erat maximus. Fusce sagittis nunc sed tellus sagittis, vitae volutpat odio faucibus. Nullam consequat ut mi a consequat. Praesent a porttitor magna. Donec placerat mollis sapien ac eleifend.
  </div>
</div>

Then we write:

const container = document.getElementById('container');
const rowToScrollTo = document.getElementById('row');

container.scrollTop = rowToScrollTo.offsetTop;

We get the scroll container with document.getElementById and assign it to container.

And we do the same with the element we want to scroll to and assign it to rowScrollTo.

Finally, we set rowScrollTo.offsetTop to container.scrollTop to do the scrolling to the div with ID row.

Conclusion

To set the scrollbar position with JavaScript, we can set the scrollTop property of the scroll container element to the value of the offsetTop property of the element we want to scroll to.

Categories
JavaScript Answers

How to Rotate a Single Object on an HTML5 Canvas?

Sometimes, we want to rotate a single object on an HTML5 canvas.

In this article, we’ll look at how to rotate a single object on an HTML5 canvas.

Rotate a Single Object on an HTML5 Canvas

To rotate a single object on an HTML5 canvas, we can use the canvas context’s translate and rotate methods.

For instance, we write:

<canvas id='canvas'></canvas>

to create the canvas element.

Then we write:

const drawImageRot = (ctx, img, x, y, width, height, deg) => {
  ctx.save()
  const rad = deg * Math.PI / 180;
  ctx.translate(x + width / 2, y + height / 2);
  ctx.rotate(rad);
  ctx.drawImage(img, width / 2 * (-1), height / 2 * (-1), width, height);
  ctx.restore();
}

const img = new Image();
img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAApgAAAKYB3X3/OAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAANCSURBVEiJtZZPbBtFFMZ/M7ubXdtdb1xSFyeilBapySVU8h8OoFaooFSqiihIVIpQBKci6KEg9Q6H9kovIHoCIVQJJCKE1ENFjnAgcaSGC6rEnxBwA04Tx43t2FnvDAfjkNibxgHxnWb2e/u992bee7tCa00YFsffekFY+nUzFtjW0LrvjRXrCDIAaPLlW0nHL0SsZtVoaF98mLrx3pdhOqLtYPHChahZcYYO7KvPFxvRl5XPp1sN3adWiD1ZAqD6XYK1b/dvE5IWryTt2udLFedwc1+9kLp+vbbpoDh+6TklxBeAi9TL0taeWpdmZzQDry0AcO+jQ12RyohqqoYoo8RDwJrU+qXkjWtfi8Xxt58BdQuwQs9qC/afLwCw8tnQbqYAPsgxE1S6F3EAIXux2oQFKm0ihMsOF71dHYx+f3NND68ghCu1YIoePPQN1pGRABkJ6Bus96CutRZMydTl+TvuiRW1m3n0eDl0vRPcEysqdXn+jsQPsrHMquGeXEaY4Yk4wxWcY5V/9scqOMOVUFthatyTy8QyqwZ+kDURKoMWxNKr2EeqVKcTNOajqKoBgOE28U4tdQl5p5bwCw7BWquaZSzAPlwjlithJtp3pTImSqQRrb2Z8PHGigD4RZuNX6JYj6wj7O4TFLbCO/Mn/m8R+h6rYSUb3ekokRY6f/YukArN979jcW+V/S8g0eT/N3VN3kTqWbQ428m9/8k0P/1aIhF36PccEl6EhOcAUCrXKZXXWS3XKd2vc/TRBG9O5ELC17MmWubD2nKhUKZa26Ba2+D3P+4/MNCFwg59oWVeYhkzgN/JDR8deKBoD7Y+ljEjGZ0sosXVTvbc6RHirr2reNy1OXd6pJsQ+gqjk8VWFYmHrwBzW/n+uMPFiRwHB2I7ih8ciHFxIkd/3Omk5tCDV1t+2nNu5sxxpDFNx+huNhVT3/zMDz8usXC3ddaHBj1GHj/As08fwTS7Kt1HBTmyN29vdwAw+/wbwLVOJ3uAD1wi/dUH7Qei66PfyuRj4Ik9is+hglfbkbfR3cnZm7chlUWLdwmprtCohX4HUtlOcQjLYCu+fzGJH2QRKvP3UNz8bWk1qMxjGTOMThZ3kvgLI5AzFfo379UAAAAASUVORK5CYII=";
img.onload = () => {
  const scale = 8;
  const srcCanvas = document.querySelector('canvas');
  const srcCtx = srcCanvas.getContext('2d');
  drawImageRot(srcCtx, img, 0, 0, 100, 100, 90)
};

to create the drawImageRot function to rotate the image.

The function takes the ctx canvas context, img img element object, x and y coordinates of the top left corner of the image, width and height of the image, and deg degrees of rotation.

In the function, we call save to save the contents.

Then we convert deg to rad radians.

Next, we call ctx.translate to translate the content by width / 2 and height / 2.

Then we call rotate to rotate the image.

After that we call drawImage to draw a rotated image.

Finally, we call restore to render the image.

Next we use the Image constructor to create the image.

Finally, we set img.onload to a function that gets the canvas with document.querySelector.

Then we call getContext to get the context.

And then we call drawImageRot to draw the image rotated 90 degrees.

Conclusion

To rotate a single object on an HTML5 canvas, we can use the canvas context’s translate and rotate methods.

Categories
JavaScript Answers

How to Stretch Images with no Antialiasing with JavaScript?

Sometimes, we want to stretch images with no antialiasing with JavaScript.

In this article, we’ll look at how to stretch images with no antialiasing with JavaScript.

Stretch Images with no Antialiasing with JavaScript

To stretch images with no antialiasing with JavaScript, we can load the image into the canvas.

Then we can copy the image pixel by pixel onto another canvas which is displayed on the screen.

For instance, we can write:

<canvas id='canvas'></canvas>

to add the canvas to display.

Then we write:

const img = new Image();
img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAApgAAAKYB3X3/OAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAANCSURBVEiJtZZPbBtFFMZ/M7ubXdtdb1xSFyeilBapySVU8h8OoFaooFSqiihIVIpQBKci6KEg9Q6H9kovIHoCIVQJJCKE1ENFjnAgcaSGC6rEnxBwA04Tx43t2FnvDAfjkNibxgHxnWb2e/u992bee7tCa00YFsffekFY+nUzFtjW0LrvjRXrCDIAaPLlW0nHL0SsZtVoaF98mLrx3pdhOqLtYPHChahZcYYO7KvPFxvRl5XPp1sN3adWiD1ZAqD6XYK1b/dvE5IWryTt2udLFedwc1+9kLp+vbbpoDh+6TklxBeAi9TL0taeWpdmZzQDry0AcO+jQ12RyohqqoYoo8RDwJrU+qXkjWtfi8Xxt58BdQuwQs9qC/afLwCw8tnQbqYAPsgxE1S6F3EAIXux2oQFKm0ihMsOF71dHYx+f3NND68ghCu1YIoePPQN1pGRABkJ6Bus96CutRZMydTl+TvuiRW1m3n0eDl0vRPcEysqdXn+jsQPsrHMquGeXEaY4Yk4wxWcY5V/9scqOMOVUFthatyTy8QyqwZ+kDURKoMWxNKr2EeqVKcTNOajqKoBgOE28U4tdQl5p5bwCw7BWquaZSzAPlwjlithJtp3pTImSqQRrb2Z8PHGigD4RZuNX6JYj6wj7O4TFLbCO/Mn/m8R+h6rYSUb3ekokRY6f/YukArN979jcW+V/S8g0eT/N3VN3kTqWbQ428m9/8k0P/1aIhF36PccEl6EhOcAUCrXKZXXWS3XKd2vc/TRBG9O5ELC17MmWubD2nKhUKZa26Ba2+D3P+4/MNCFwg59oWVeYhkzgN/JDR8deKBoD7Y+ljEjGZ0sosXVTvbc6RHirr2reNy1OXd6pJsQ+gqjk8VWFYmHrwBzW/n+uMPFiRwHB2I7ih8ciHFxIkd/3Omk5tCDV1t+2nNu5sxxpDFNx+huNhVT3/zMDz8usXC3ddaHBj1GHj/As08fwTS7Kt1HBTmyN29vdwAw+/wbwLVOJ3uAD1wi/dUH7Qei66PfyuRj4Ik9is+hglfbkbfR3cnZm7chlUWLdwmprtCohX4HUtlOcQjLYCu+fzGJH2QRKvP3UNz8bWk1qMxjGTOMThZ3kvgLI5AzFfo379UAAAAASUVORK5CYII=";
img.onload = () => {
  const scale = 8;
  const srcCanvas = document.createElement('canvas');
  srcCanvas.width = img.width;
  srcCanvas.height = img.height;

  const srcCtx = srcCanvas.getContext('2d');
  srcCtx.drawImage(img, 0, 0);
  const srcData = srcCtx.getImageData(0, 0, img.width, img.height).data;

  const dstCanvas = document.getElementById('canvas');
  dstCanvas.width = img.width * scale;
  dstCanvas.height = img.height * scale;
  const dstCtx = dstCanvas.getContext('2d');

  let offset = 0;
  for (let y = 0; y < img.height; ++y) {
    for (let x = 0; x < img.width; ++x) {
      const r = srcData[offset++];
      const g = srcData[offset++];
      const b = srcData[offset++];
      const a = srcData[offset++] / 100.0;
      dstCtx.fillStyle = 'rgba(' + [r, g, b, a].join(',') + ')';
      dstCtx.fillRect(x * scale, y * scale, scale, scale);
    }
  }
};

to create an img element with the Image constructor.

Then we set the src property of the image to load the image with the given URL.

Next, we set the img.onload property to a function that creates the canvas.

We set the width and height of the canvas to the width and height of the image with:

srcCanvas.width = img.width;
srcCanvas.height = img.height;

Then we draw the image onto the canvas with:

const srcCtx = srcCanvas.getContext('2d');
srcCtx.drawImage(img, 0, 0);
const srcData = srcCtx.getImageData(0, 0, img.width, img.height).data;

Next, we get the destination canvas element which we created with:

const dstCanvas = document.getElementById('canvas');

And we set the width and height of the destination canvas with:

dstCanvas.width = img.width * scale;
dstCanvas.height = img.height * scale;

And finally, we copy each pixel from the source canvas to the destination canvas with:

let offset = 0;
for (let y = 0; y < img.height; ++y) {
  for (let x = 0; x < img.width; ++x) {
    const r = srcData[offset++];
    const g = srcData[offset++];
    const b = srcData[offset++];
    const a = srcData[offset++] / 100.0;
    dstCtx.fillStyle = 'rgba(' + [r, g, b, a].join(',') + ')';
    dstCtx.fillRect(x * scale, y * scale, scale, scale);
  }
}

Now we can see the pixelated version of the original image when we run the code.

Conclusion

To stretch images with no antialiasing with JavaScript, we can load the image into the canvas.

Then we can copy the image pixel by pixel onto another canvas which is displayed on the screen.