Categories
JavaScript Answers

How to select Fabric.js object programmatically with JavaScript?

Sometimes, we want to select Fabric.js object programmatically with JavaScript.

In this article, we’ll look at how to select Fabric.js object programmatically with JavaScript.

How to select Fabric.js object programmatically with JavaScript?

To select Fabric.js object programmatically with JavaScript, we can use the canvas.setActiveObject method.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/460/fabric.min.js"></script>

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

We add the fabric.js script and the canvas element.

Then we write:

const canvas = new fabric.Canvas('canvas');

canvas.add(new fabric.Rect({
  left: 80,
  top: 80,
  width: 75,
  height: 50,
  fill: 'green',
  stroke: 'black',
  strokeWidth: 3,
  padding: 10
}));

canvas.add(new fabric.Circle({
  left: 50,
  top: 50,
  radius: 30,
  fill: 'gray',
  stroke: 'black',
  strokeWidth: 3
}));

canvas.setActiveObject(canvas.item(0));

We use the fabric.Canvas constructor with the ID of the canvas to create a fabric canvas.

Then we call canvas.add to add a rectangle and circle at various positions, shapes, fill and sizes.

Then we set the select item to the item we added first, which is the rectangle, by writing:

canvas.setActiveObject(canvas.item(0));

We call canvas.setActiveObject with canvas.item(0) to select the first object to be selected,.

Conclusion

To select Fabric.js object programmatically with JavaScript, we can use the canvas.setActiveObject method.

Categories
JavaScript Answers

How to run code after all images have loaded with JavaScript?

Sometimes, we want to run code after all images have loaded with JavaScript.

In this article, we’ll look at how to run code after all images have loaded with JavaScript.

How to run code after all images have loaded with JavaScript?

To run code after all images have loaded with JavaScript, we can create a promise that resolves when all the images are loaded.

For instance, we write:

<img src='https://picsum.photos/200/300'>
<img src='https://picsum.photos/200'>

to add all images.

Then we write:

const imgLoadPromise = img => {
  return new Promise(resolve => {
    img.onload = () => {
      resolve()
    }
  })
}

(async () => {
  const promises = [...document.images]
    .filter(img => !img.complete)
    .map(imgLoadPromise)
  await Promise.all(promises)
  console.log('success')
})()

We create the imgLoadPromise function that takes an img element.

It returns a promise that resolves when img.onload is run. When that’s run, the image is loaded successfully.

Then we create a promise that gets all the images with document.images and spread them into an array.

Next, we call filter with a callback to return with ones that haven’t loaded.

Then we call map with imgLoadPromise to map them to promises.

And then we call Promise.all with promises to wait for all of them to load.

Therefore, when all the images are loaded, 'success' is logged in the console.

Conclusion

To run code after all images have loaded with JavaScript, we can create a promise that resolves when all the images are loaded.

Categories
JavaScript Answers

How to validate currency with JavaScript regex?

Sometimes, we want to validate currency with JavaScript regex.

In this article, we’ll look at how to validate currency with JavaScript regex.

How to validate currency with JavaScript regex?

To validate currency with JavaScript regex, we use the following regex:

/(?=.*?\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|\d+)?(\.\d{1,2})?$/

The (?=.*?\d) part makes sure that the string starts with a number.

^\$?(([1-9]\d{0,2} makes sure the number starts with 1 to 9.

(,\d{3})*) checks that the number has 0 or more groups of 3 digits after the start of the number separated by commas.

We also have \d+ to make the 3 digit groups optional.

Finally, we have ?(\.\d{1,2})?$ to make sure that the number optionally ends with a decimal point and 0 to 2 digits.

Conclusion

To validate currency with JavaScript regex, we use the following regex:

/(?=.*?\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|\d+)?(\.\d{1,2})?$/
Categories
JavaScript Answers

How to convert \n to HTML line breaks?

Sometimes, we want to convert \n to HTML line breaks.

In this article, we’ll look at how to convert \n to HTML line breaks.

How to convert \n to HTML line breaks?

To convert \n to HTML line breaks, we can set the white-space CSS property to pre-line.

For instance, we write:

<span style="white-space: pre-line"></span>

to add a span with the white-space CSS property set to pre-line.

Then we write:

const span = document.querySelector('span')
span.textContent = 'foo \n bar'

We select the span with document.querySelector.

And then we set the textContent of the span to 'foo \n bar' to set that as the content of the span.

Now we should see:

foo
bar

displayed on the screen.

Conclusion

To convert \n to HTML line breaks, we can set the white-space CSS property to pre-line.

Categories
Chart.js JavaScript Answers

How to remove the vertical line in the Chart.js line chart?

Sometimes, we want to remove the vertical line in the Chart.js line chart.

In this article, we’ll look at how to remove the vertical line in the Chart.js line chart.

How to remove the vertical line in the Chart.js line chart?

To remove the vertical line in the Chart.js line chart, we can set the options.scales.x.grid.display property to false.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>

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

to add the Chart.js script and canvas for the chart.

Then we write:

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Monday', 'Tuesday', 'Wednesday'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      borderWidth: 1,
      borderColor: 'green'
    }]
  },
  options: {
    scales: {
      x: {
        grid: {
          display: false
        }
      },
    }
  }
});

to set options.scale.x.grid.display to false to hide the vertical lines in the background.

Now we should only see the horizontal lines displayed in the background.

Conclusion

To remove the vertical line in the Chart.js line chart, we can set the options.scales.x.grid.display property to false.