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?

Sometimes, we want to display pie chart data values of each slice in Chart.js and JavaScript.

In this article, we’ll look at how to display pie chart data values of each slice in Chart.js and JavaScript.

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.

Conclusion

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

Categories
JavaScript Answers

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

Sometimes, we want to find all the days in a month with the JavaScript Date object.

In this article, we’ll look at how to find all the days in a month with the JavaScript Date object.

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.

Conclusion

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.

Categories
JavaScript Answers

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

Sometimes, we want to resize then crop an image with HTML canvas and JavaScript.

In this article, we’ll look at how to resize then crop an image with HTML canvas and JavaScript.

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.

Conclusion

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.

Categories
JavaScript Answers

How to Compute the Intersection of Two Arrays in JavaScript?

Sometimes, we want to compute the intersection of two arrays in JavaScript.

In this article, we’ll look at how to compute the intersection of two arrays in JavaScript.

Compute the Intersection of Two Arrays in JavaScript

To compute the intersection of two arrays in JavaScript, we can use the array filter method with the includes method to get the elements that are in both arrays and return them in an array.

For instance, we can write:

const arr1 = ["mike", "sue", "tom", "kathy", "henry"];
const arr2 = ["howey", "jim", "sue", "jennifer", "kathy", "hank", "alex"];

const result = arr1.filter((n) => {
  return arr2.includes(n);
});
console.log(result)

to get all the name strings that are in both arr1 and arr2 by calling arr1.filter with a callback that returns the condition that the items are also included with arr2 with arr2.includes(n) .

Then we assign the returned result to result .

Therefore, result is [“sue”, “kathy”] .

Conclusion

To compute the intersection of two arrays in JavaScript, we can use the array filter method with the includes method to get the elements that are in both arrays and return them in an array.