Categories
JavaScript Answers

How to Convert an SVG to an Image in the Browser?

Sometimes, we may want to convert an SVG image into another image format like JPEG and PNG in our web app.

We can do this completely from the client-side.

In this article, we’ll look at how to convert an SVG into another image format completely from the client-side.

Convert an SVG to an Image

We can convert an SVG to an image completely with client-side JavaScript code.

To do this, we write:

const svg = `
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" baseProfile="full" width="300" height="200">
   <rect width="100%" height="100%" fill="red" />
   <circle cx="150" cy="100" r="80" fill="green" />
   <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text>
</svg>
`
svgToPng(svg, (imgData) => {
  const pngImage = document.createElement('img');
  document.body.appendChild(pngImage);
  pngImage.src = imgData;
});

function svgToPng(svg, callback) {
  const url = getSvgUrl(svg);
  svgUrlToPng(url, (imgData) => {
    callback(imgData);
    URL.revokeObjectURL(url);
  });
}

function getSvgUrl(svg) {
  return URL.createObjectURL(new Blob([svg], {
    type: 'image/svg+xml'
  }));
}

function svgUrlToPng(svgUrl, callback) {
  const svgImage = document.createElement('img');
  document.body.appendChild(svgImage);
  svgImage.onload = () => {
    const canvas = document.createElement('canvas');
    canvas.width = svgImage.clientWidth;
    canvas.height = svgImage.clientHeight;
    const canvasCtx = canvas.getContext('2d');
    canvasCtx.drawImage(svgImage, 0, 0);
    const imgData = canvas.toDataURL('image/png');
    callback(imgData);
    document.body.removeChild(imgPreview);
  };
  svgImage.src = svgUrl;
}

We have the svg variable with the SVG string.

To start, we call svgToPng with the svg string and the callback .

Then we create an img element with document.createElement and assign it to pngImage .

Then we call document.body.appendChild to append the img element to the body.

Then we set pngImage.src to the URL that we’ll get from the callback imgData parameter.

Then we create the svgToPng function which takes an svg string and the callback function.

Next, we create the svgToPng function that takes the svg and callback .

It calls the getSvgUrl function to get the base64 URL from the svg .

Then we call the svgUrlToPng functioon that does the conversion with the url and the callback to get the image data.

To create the getSvgUrl function, we just call URL.createObjectURL with the svg string converted to a Blob instance to return the base64 version of the SVG.

Then we create the svgUrlToPng function that puts the SVG into a canvas.

We do this so that we can extract the canvas content as an image binary later.

In the svgUrlToPng function, we create an img element.

Then we append the created element to the body with document.body.appendChild .

Then we set the width and height of the canvas from the svgImage sizes.

And then we call drawImage on the canvas context to draw the SVG base64 URL into the canvas.

Next, we call toDataURL with the MIME type of the image format to convert to.

Then we call the callback so that the callback runs with the imgData image data passed into it.

Then we call documen.body.removeChild to remove the preview.

We also set svgImage.src to the svgURL to add a preview.

Conclusion

We can convert an SVG into another image format with JavaScript.

Categories
JavaScript Answers

How to Remove Everything After a Certain Character?

Sometimes, we may want to remove everything after a given character in our JavaScript string.

In this article, we’ll look at how to remove everything after a certain character.

String.prototype.split

We can split a string with the split method.

For instance, we can write:

const url = '/Controller/Action?id=1111&value=2222'
const [path] = url.split('?')
console.log(path)

to get the path string before the question mark with split .

split returns an array of substrings separated by the given character.

So we can destructure the returned array and get the first item.

Therefore, path is: '/Controller/Action’ .

String.prototype.indexOf and String.prototype.substring

The indexOf method lets us get the index of the given character in a string.

We can use it with the substring method to extract the substring from the beginning to the given index returned by indexOf .

For instance, we can write:

const url = '/Controller/Action?id=1111&value=2222'
const path = url.substring(0, url.indexOf('?'));
console.log(path)

We call url.indexOf('?') to get the index of the question mark character.

Then we pass that into substring as the 2nd argument.

0 as the first argument means we get the substring from the first character to the index passed in the 2nd argument.

So path has the same value as before.

Regex Replace

We can also call the string replace method with a regex to remove the part of the string after a given character.

For instance, we can write:

const url = '/Controller/Action?id=1111&value=2222'
const path = url.replace(/\?.*/, '');
console.log(path)

The /\?.*/ regex matches everything from the question to the end of the string.

Since we passed in an empty string as the 2nd argument, all of that will be replaced by an empty string.

replace returns a new string with the replacement applied to it.

So path is the same value as before.

Conclusion

There are several ways we can use to extract the part of the string after the given character with several string methods.

Categories
JavaScript Answers

How to Add a Right-Click Menu to a Webpage?

Sometimes, we may want to add a right-click menu to a webpage.

In this article, we’ll look at how to add a right-click menu to a webpage with JavaScript.

Listening to the contextmenu and click Events

To open a context menu on right-click, we attach an event listener to the contextmenu event and call preventDefault to prevent the default action in the event listener.

The default action is to open the browser’s context menu.

Then after that, we can add code to open the menu.

To close the menu when we left-click on the page, we add a click event listener and then set the styles to close the menu.

To do this, we write the following HTML to create a context menu:

<ul id="ctxMenu">
  <li>Save</li>
  <li>Save As</li>
  <li>Open</li>
</ul>

Then we add some CSS styles by writing:

#ctxMenu {
  border: 1px solid black;
  padding: 10px;
  list-style-type: none;
  display: none;
  position: absolute;
  width: 200px;
}

We add a border and make position absolute so that the context menu will show where we right-click on the mouse.

And we set display to none so that we don’t show the menu initially.

Next, we add the event listeners by writing the following JavaScript code:

const ctxMenu = document.getElementById("ctxMenu");

window.addEventListener("contextmenu", (event) => {
  event.preventDefault();
  ctxMenu.style.display = "block";
  ctxMenu.style.left = (event.pageX - 10) + "px";
  ctxMenu.style.top = (event.pageY - 10) + "px";
});

window.addEventListener("click", (event) => {
  ctxMenu.style.display = "";
  ctxMenu.style.left = "";
  ctxMenu.style.top = "";
});

We call window.addEventListener to listen to the events on the whole page.

In the contextmenu event handler, we call event.preventDefault to prevent the default action when we right-click, which is to open the browser’s context menu.

Then we set display to 'block' to show the ul as a block-level element.

And we set left and top to the position where the mouse pointer is right-clicked.

In the click event listener, we set the display , left and top properties all to an empty string to remove all the styles and use the ones from CSS.

Now when we right-click on the page, we see our context menu displayed instead of the browser’s menu.

Conclusion

We can create our own context menu on a web page by creating our own HTML, CSS, and JavaScript code.

Categories
JavaScript Answers

How to Delete a Client-Side Cookie with JavaScript?

Sometimes, we may store cookies on the client-side to keep track of things on the user’s device.

And sometimes, we want to delete cookies from the user’s browser.

In this article, we’ll look at how to delete a client-side cookie with JavaScript.

Create Our Own Function

Browsers don’t comes with any API to let us delete cookies easily.

Therefore, we’ve to create our own function to delete cookies from a user’s browser.

To do this, we write:

const getCookie = (name) => {
  return document.cookie.split(';').some(c => {
    return c.trim().startsWith(name + '=');
  });
}

const deleteCookie = (name, path, domain) => {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? ";path=" + path : "") +
      ((domain) ? ";domain=" + domain : "") +
      ";expires=Thu, 01 Jan 1970 00:00:01 GMT";
  }
}

document.cookie = 'foo=bar'
deleteCookie('foo')

We create the getCookie function to check for a cookie with the given name value.

We do that by splitting the document.cookie string by the semicolon.

Then we call startsWith on the split string with the name and equal sign to check if there’s a cookie with the given key.

Next, we define the deleteCookie function that checks if the cookie with the given key exists with getCookie .

If it does, then we add a expires date and time to the end of the string by appending:

";expires=Thu, 01 Jan 1970 00:00:01 GMT"

to it.

The way to delete a cookie is to set its expiry date to a date and time before the current date and time.

Therefore, when we set the cookie in the 2nd last line and call deleteCookie with the same key right after, we won’t see the cookie being set since it’s added and removed immediately after.

Conclusion

We can delete a client-side cookie from the user’s browser by setting the expiry date of the cookie with the given key to a date and time before the current date and time.

Categories
JavaScript Answers

How to Get the Height of the Entire Document with JavaScript?

Sometimes, we may want to get the height of the entire document with JavaScript.

In this article, we’ll look at how to get the height of the entire document with JavaScript.

Getting the Height of a Document

To get the height of a document, we can get the max of the scrollHeight, offsetHeight, or clientHeight properties.

For instance, we can write:

const body = document.body;
const html = document.documentElement;

const height = Math.max(body.scrollHeight, body.offsetHeight,
  html.clientHeight, html.scrollHeight, html.offsetHeight);
console.log(height)

The document can be stored in the document.body or document.documentElement properties depending on the browser used.

scrollHeight is a read-only property is a measurement of the height of an element’s content including the area that’s not visible on the page.

offsetHeight is a read-only property that returns the height of the element, including the vertical padding and borders as an integer.

clientHeight is a read-only property is the inner height of an element in pixels.

It includes the padding but excludes borders, margins, and horizontal scrollbars if they’re present.

Therefore, the max value between those would be the document’s height which includes everything.

The getBoundingClientRect Method

We can also use the getBoundClientRect method on the document element to get the height of it.

To use it, we write:

const body = document.body;
const html = document.documentElement;

const height = Math.max(body.getBoundingClientRect().height, html.getBoundingClientRect().height);
console.log(height)

We get the height of content of the document with the getBoundingClientRect method.

It returns an object with the height property to get the height of the content of the document.

The height is in pixels.

Conclusion

There’re various properties we can use to get the height of a document with JavaScript.