Categories
JavaScript Answers

How to Check if a JavaScript Function is a Constructor?

Sometimes, we want to check if a JavaScript function is a constructor

In this article, we’ll look at how to check if a JavaScript function is a constructor.

Check if a JavaScript Function is a Constructor

To check if a JavaScript function is a constructor, we can check if we can use the new operator with it.

To do this, we write:

const handler = {
  construct() {
    return handler
  }
}

const isConstructor = x => {
  try {
    return !!(new(new Proxy(x, handler))())
  } catch (e) {
    return false
  }
}

console.log(isConstructor(() => {}))
console.log(isConstructor(class {}))

We create a proxy in the isConstructor function that takes any variable x .

Then we use the new operator on the proxy version of x , which we create with:

(new Proxy(x, handler))()

If that works, then we know the x is a constructor since we create a new instance of x .

Otherwise, an error is throw and false is returned.

Therefore, the first console log logs false and the 2nd one logs true .

Categories
JavaScript Answers jQuery

How to Get the Context of a Canvas with jQuery?

Sometimes, we want to get the context of a Canvas with jQuery

In this article, we’ll look at how to get the context of a Canvas with jQuery.

Get the Context of a Canvas with jQuery

To get the context of a Canvas with jQuery, we call the get method with the index of the element we want to get.

Then we can call getContext on the returned element.

For instance, if we have the following canvas:

<canvas width='200' height='200'></canvas>

We write:

const ctx = $("canvas").get(0).getContext('2d');  
console.log(ctx)

to select canvas elements with $(“canvas”) .

Then we use get(0) to get the first canvas element selected.

And then we call getContext on that to get the context.

Conclusion

To get the context of a Canvas with jQuery, we call the get method with the index of the element we want to get.

Then we can call getContext on the returned element.

Categories
JavaScript Answers

How to Display Pie Chart Data Values of Each Slice in Chart.js and JavaScript?

To display pie chart data values of each slice in Chart.js and JavaScript, we can use the chartjs-plugin-labels plugin.

To use it, we write the following HTML:

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

<script src='https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js
'></script>

<canvas width='200' height='200'></canvas>

to add the script tags for Chart.js, the plugin, and the canvas for the chart.

Next, we write:

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')

const data = {
  datasets: [{
    data: [
      11,
      16,
      7,
      3,
      14
    ],
    backgroundColor: [
      "#FF6384",
      "#4BC0C0",
      "#FFCE56",
      "#E7E9ED",
      "#36A2EB"
    ],
    label: 'My dataset' // for legend
  }],
  labels: [
    "Red",
    "Green",
    "Yellow",
    "Grey",
    "Blue"
  ]
};

new Chart(ctx, {
  type: 'pie',
  data,
  options: {
    plugins: {
      labels: {
        render: 'value',
        precision: 0,
        showZero: true,
        fontSize: 12,
        fontColor: '#fff',
        fontStyle: 'normal',
        fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
        textShadow: true,
        shadowOffsetX: -5,
        shadowOffsetY: 5,
        shadowColor: 'rgba(255,0,0,0.75)',
        arc: true,
        position: 'default',
        overlap: true,
        showActualPercentages: true,
        images: [{
          src: 'image.png',
          width: 16,
          height: 16
        }],
        outsidePadding: 4,
        textMargin: 4
      }
    }
  }
});

We have the data object with the chart data and the color of the slices stored in backgroundColor.

Then we have some options for the text in the plugins.labels property.

Options include fontColor , fontStyle , fontFamily , fontSize and more that will be shown in the pie slices.

Now each pie slice should have the number corresponding to the slice size in it.

Categories
JavaScript Answers

How to Find All the Days in a Month with the JavaScript Date Object?

To find all the days in a month with the JavaScript Date object, we can create an array with the all dates of the month in it.

To do this, we write:

const getDaysInMonth = (month, year) => {
  return new Array(31)
    .fill('')
    .map((v, i) => new Date(year, month - 1, i + 1))
    .filter(v => v.getMonth() === month - 1)
}

console.log(getDaysInMonth(2, 2020))

We create an array with 31 entries initally with new Array(31) .

Then we call fill to fill the empty slots with empty strings.

Next, w call map to map each index, with the dates of the month with new Date(year, month — 1, i + 1) .

JavaScript date months starts with 0 for January to 11 for December, so we’ve to subtract month by 1.

And we’ve to add 1 to 1 to get all the days of the month.

If the day of the month exceeds, the max, the month will be incremented by 1.

So we can just call filter to filter out all the dates with the month that’s 1 more than month — 1 to get the right dates for month .

Therefore, the console log should have 29 days in it since February 2020 has 29 days.

Categories
JavaScript Answers

How to Resize Then Crop an Image with HTML Canvas and JavaScript?

To resize then crop an image with HTML canvas and JavaScript, we can call the drawImage method with the original image with the coordinates of the boundaries of the image we want to crop.

For instance, if we have the following HTML:

Image: <br/>
<img src="https://i.stack.imgur.com/I4jXc.png" /><br/>
Canvas: <br/>
<canvas id="canvas" width="300" height="300"></canvas>

we write:

const image = new Image()
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d');

image.src = 'https://i.stack.imgur.com/I4jXc.png';

image.onload = () => {
  ctx.drawImage(image,
    70, 20,
    50, 50,
    0, 0,
    100, 100);
}

to do the cropping.

We create an image element with the Image constructor.

Then we get the canvas with document.getElementById .

Next, we get the canvas context with getContext .

Then we setr the src property of thr image to the image URL.

This will trigger the image.onload method to run.

In the onload method, we call drawImage with the

  • image
  • x and y coordinates of the top left corner
  • width of the part of the source image to get relative to the top left corner
  • height of part of source image to get relative to the top left corner
  • x and y coordinates of the top left corner of the cropped image
  • width and height of the cropped image

in this order.

Therefore, we should get the ‘o’ from the word ‘Google’ in the image.