Categories
JavaScript Answers

How to Determine if a String is a Base64 String Using JavaScript?

To determine if a string is a base64 string using JavaScript, we can check if a base64 string against a regex.

For instance, we can write:

const base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;

console.log(base64regex.test("abc"));
console.log(base64regex.test("U29tZVN0cmluZ09idmlvdXNseU5vdEJhc2U2NEVuY29kZWQ="));

We define the base64regex that matches any string that has 4 letters and numbers in the first group.

Then we check of groups of 2 letters and number or groups of 3 letters and numbers with equal signs after them for padding.

Therefore, the first console log will log false.

And the 2nd one will log true.

Categories
JavaScript Answers

How to Wrap Text in a Canvas Element with JavaScript?

To wrap text in a canvas element with JavaScript, we have to do the calculation for wrapping the text ourselves.

For instance, we write:

<canvas style='width: 300px; height: 300px'></canvas>

to create the canvas.

Then we write:

const wrapText = (ctx, text, x, y, maxWidth, lineHeight) => {
  const words = text.split(' ');
  let line = '';
  for (const [index, w] of words.entries()) {
    const testLine = line + w + ' ';
    const metrics = ctx.measureText(testLine);
    const testWidth = metrics.width;
    if (testWidth > maxWidth && index > 0) {
      ctx.fillText(line, x, y);
      line = w + ' ';
      y += lineHeight;
    } else {
      line = testLine;
    }
  }
  ctx.fillText(line, x, y);
}

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const maxWidth = 300;
const lineHeight = 24;
const x = (canvas.width - maxWidth) / 2;
const y = 70;
const text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eu lacinia lorem, eget luctus odio. Pellentesque eget rhoncus eros. Suspendisse a finibus nisl, non porta erat. Donec interdum turpis ac urna egestas tempus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. ';

ctx.font = '15pt Calibri';
ctx.fillStyle = '#555555';
wrapText(ctx, text, x, y, maxWidth, lineHeight);

We create the wrapText function that takes the ctx canvas context.

text is the text to wrap.

x and y are coordinates of the top left corner of the text.

maxWidth is the max width of a line,

And lineHeight is the height of a line of text.

In the function, we split the text with split by a space into an array.

Then we loop through the returned string array entries with the entries method.

Next, we create a line of text with:

const testLine = line + w + ' ';

Next, we call ctx.measureText with testLine to get the dimensions of the text.

Then we have a if statement that checks if testwidth is bigger than maxWidth and index is bigger than 0.

If they’re both true, then we call fillText with the line then we set line to w + ' ' to get the text in the next line.

Then we have y += lineHeight to move the y coordinate of the text for the next line.

Otherwise, we don’t need to wrap the text and we set line to testLine.

Finally, we call ctx.fillText to draw the text.

Next, we get the canvas with querySelector.

Then we get the context with getContext.

And then we set the maxWidth of the text and the lineHeight.

Next, we calculate the x and y values of the top left corner of the text.

Then we set text to a string with the text we want to render.

And then we set the font and fillStyle of the text.

Finally, we call wrapText to draw the text.

Categories
JavaScript Answers

How to Set the Z-index of an HTML5 Canvas with JavaScript?

To set the z-index of an HTML5 canvas with JavaScript, we can use the canvas context’s globalCompositeOperation property.

For instance, we write:

<canvas style='width: 300px; height: 300px'></canvas>

to add a canvas element.

Then we write:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
let cx = 50;

ctx.globalCompositeOperation = 'destination-over';

const randomColor = () => {
  return ('#' + Math.floor(Math.random() * 16777215).toString(16));
}

const drawCircle = () => {
  ctx.beginPath();
  ctx.arc(cx, 50, 20, 0, Math.PI * 2);
  ctx.closePath();
  ctx.fillStyle = randomColor();
  ctx.fill();
}

for (let i = 0; i < 5; i++) {
  drawCircle();
  cx += 20;
}

We get the canvas element with document.querySelector.

Then we call getContext to get the context.

Then we set globalCompositionOperator to 'destination-over' to draw the new shape behind the current shapes.

Next, we create the randomColor function to return a random color code.

Then we create the drawCircle function that calls ctx.arc to draw a circle.

The first 2 arguments are x and y coordinates of the center. The 3rd argument is the radius.

And the last argument is the angle of the arc, which is Math.PI * 2 since we want to draw a circle.

We call closePath to draw the arc.

fillStyle is the color of the circle.

And we call fill to fill the circle with the fill color.

Finally, we use the for loop to draw 5 circles.

Now we should see that the ones that are drawn later are behind the ones that are drawn earlier.

Categories
JavaScript Answers

How to Convert a JavaScript Object to an Array?

To convert a JavaScript object to an array, we can use the Object.entries method to get the key-value pairs from the object into an array.

Then we can use the JavaScript array’s map method to return each entry in an array.

For instance, we can write:

const input = {
  "fruit": ["mango", "orange"],
  "veg": ["carrot"]
};

const output = Object.entries(input).map(([key, val]) => {
  return {
    type: key,
    name: val
  };
});

console.log(output)

We have the input object that has several properties.

Then we call Object.entries with input to return an array of key-value pair arrays.

Next, we call map with a callback that destructures the key-value pair from the parameter and return an object with the key and val set as values of the object.

Therefore, output is:

[
  {
    "type": "fruit",
    "name": [
      "mango",
      "orange"
    ]
  },
  {
    "type": "veg",
    "name": [
      "carrot"
    ]
  }
]
Categories
JavaScript Answers

How to Convert inline SVG to Base64 string with JavaScript?

To convert inline SVG to base64 string with JavaScript, we can use the serializeToString method available with a XMLSerializer instance to parse the svg element to an XML string.

Then we call window.btoa to convert the string into a base64 string.

For instance, if we have:

<svg height="100" width="100">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>

Then we write:

const s = new XMLSerializer().serializeToString(document.querySelector("svg"))
const encodedData = window.btoa(s);
console.log(encodedData)

We call serializeToString with the svg element object that’s returned with document.querySelector.

Then we call window.btoa on the string returned by serializeToString.

Therefore, from the console log, we get:

PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTAwIiB3aWR0aD0iMTAwIj4KICA8Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI0MCIgc3Ryb2tlPSJibGFjayIgc3Ryb2tlLXdpZHRoPSIzIiBmaWxsPSJyZWQiLz4KPC9zdmc+

logged as a result.