Categories
JavaScript Answers

How to Resize HTML5 Canvas to Fit the Window?

Sometimes, we may want to resize an HTML5 canvas to fit the window that it’s in.

In this article, we’ll look at how to resize an HTML5 canvas to fit the window.

Setting the width and height Properties of the Canvas

We can just set the width and height properties of the canvas as the window resizes to set the width and height of the canvas to change its size.

For instance, we can write:

const draw = (canvas) => {
  const ctx = canvas.getContext("2d");
  ctx.beginPath();
  ctx.arc(95, 50, 40, 0, 2 * Math.PI);
  ctx.stroke();
}

const canvas = document.querySelector("canvas");
canvas.width = window.innerWidth
canvas.height = window.innerHeight
draw(canvas)

window.addEventListener('resize', () => {
  canvas.width = window.innerWidth
  canvas.height = window.innerHeight
  draw(canvas)
})

to change the size of the canvas initialize to the window’s dimensions with:

canvas.width = window.innerWidth
canvas.height = window.innerHeight

And we do the same thing in the resize event listener, which we added with the addEventListener method.

When the canvas resizes the content disappears, so they have to be drawn again whenever we resize the canvas by setting the width and height properties.

Set the Size with CSS

We can also set the size of the canvas with CSS to make it fill the screen.

For instance, we can write the following HTML:

<canvas></canvas>

And the following CSS:

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
}

canvas {
  background-color: #ccc;
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
}

to set the canvas’s width and height both to 100%.

We also set the position to absolute and top , left , right , and bottom to 0 to make the canvas fill the screen.

Also, we make the html and body elements fill the screen by setting the width and height to 100%.

And we can draw on it with:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();

We draw a circle with the arc method.

We have the center x and y coordinates, radius, and start and end angles in radians as arguments in this order.

Conclusion

We can resize the canvas to fit the screen with JavaScript or CSS.

Categories
JavaScript Answers

How to Compare the Date Part of a Date Object Only Without Comparing the Time in JavaScript?

Sometimes, we may want to compare the date part of a date only without comparing the time in our JavaScript app.

In this article, we’ll look at how to compare the date without comparing the time with JavaScript.

Date.prototype.setHours

To compare dates without comparing the time portion, we can set both dates to midnight by using the setHours method that comes with JavaScript date objects.

For instance, we can write:

const date1 = new Date(2021, 1, 1, 1, 1, 1)
date1.setHours(0, 0, 0, 0)

const date2 = new Date(2021, 2, 1)
date2.setHours(0, 0, 0, 0)

console.log(+date2 > +date1)

We call setHours on date1 to set the hours, minutes, and seconds of date1 all to 0.

This will set the date to midnight.

Then we can compare them both without the time part with the > operator as we did in the last line,

To be safe, we convert them both to timestamps first with the + operator.

Therefore, the console log should show true since date2 is ahead of date1 .

To be even safer, we can do both date comparisons after converting them both to UTC date-times.

To do this, we write:

const date1 = new Date(2021, 1, 1, 1, 1, 1)
const date1Copy = new Date(Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate()));
date1Copy.setHours(0, 0, 0, 0)

const date2 = new Date(2021, 2, 1)
const date2Copy = new Date(Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate()));
date2Copy.setHours(0, 0, 0, 0)

console.log(+date2Copy > +date1Copy)

We call Date.UTC with the date parts retrieved from date1 and date2 to create a UTC timestamp.

Then we pass them into the Date constructor to create new date objects.

Then we call setHours on the copied dates and then do the comparison with them.

And we should get the same result from the console log.

Moment.js

The moment.js library has the isAfter method that lets us compare 2 date-times without the time part.

To do this, we write:

const date1 = new Date(2021, 9, 20, 12, 0, 0);
const date2 = new Date(2021, 9, 20, 12, 1, 0);
const isAfter = moment(date2).isAfter(date1, 'day');

console.log(isAfter)

We call isAfter on the moment date object created with the date2 date object.

And we pass in 'day' into the 2nd argument to exclude the time part of each date from the comparison.

Therefore, isAfter should be false as a result since they’re both the same date excluding the time part.

Conclusion

We can use native JavaScript date methods or moment.js to compare dates without the time part.

Categories
JavaScript Answers

How to Get the Hours Difference Between Two Dates with Moment.js?

Moment.js is a popular JavaScript date and time manipulation library that we can use to calculate various things with date and time.

In this library, we’ll look at how to get the hours difference between 2 dates with moment.js

The moment.duration Method

The moment.duration lets us calculate the duration between 2 dates.

We can combine it with the diff method to calculate the hours difference between 2 dates.

For instance, we can write:

const startTime = moment('2021-01-01')  
const end = moment('2021-02-01')  
const duration = moment.duration(end.diff(startTime));  
const hours = duration.asHours();  
console.log(hours)

We call end.diff(startTime) to calculate the difference between end and startTime .

Then we call moment.duration to get the moment duration.

And finally, we call asHours to get the duration as hours.

Therefore, hours is 744 hours.

Moment.js fromNow and from Methods

We can use the fromNow method to get a human readable string of the difference between a date and now.

For instance, we can write:

const diff = moment('2021-01-01').fromNow()   
console.log(diff)

And we get something like ‘2 months ago’ .

We can use moment.js from method to get a human-readable string between the difference between 2 dates.

For instance, we can write:

const a = moment('2021-01-01');  
const b = moment('2021-02-01');  
const diff = a.from(b);  
console.log(diff)

And we get 'a month ago’ as a value of diff since February 1, 2021 is 1 month ahead of January 1, 2021.

Moment.js diff Method with Unit as the Second Argument

We can pass in a second argument to the diff method to return the difference in the unit specified.

For instance, we can write:

const a = moment('2021-01-01');  
const b = moment('2021-02-01');  
const diff = a.diff(b, 'hours');  
console.log(diff)

We get the difference between date-time a and b .

And a is behind b by 1 month, so we get -744 as the result of diff .

The 2nd argument is 'hours' so the result is in hours.

Conclusion

We can get the difference between 2 dates with the units we specified with various moment.js methods.

Also, we can get human readable durations with moment.js.

Categories
JavaScript Answers

How to Simulate a Keypress Event Programmatically with JavaScript?

dispatchEvent Method

We can call the dispatchEvent method to trigger an event of our choice.

For instance, we can write:

window.addEventListener('keydown', (e) => {
  console.log(e)
})

window.dispatchEvent(new KeyboardEvent('keydown', {
  'key': 'a'
}));

to listen to the keydown event and trigger it.

We call addEventListener with 'keydown' to listen to the keydown event.

Then to trigger the keydown event, we call window.dispatchEvent with a KeyboardEvent instance.

We pass in the type of keyboard event to trigger into the first argument of the constructor.

And we pass in an object with the options to set in the event object into the 2nd argument.

Therefore, after dispatchEvent is run, then e.key should be 'a' when logged in the callback.

We can set more options in the object.

For instance, we can write:

window.addEventListener('keydown', (e) => {
  console.log(e)
})

window.dispatchEvent(new KeyboardEvent('keydown', {
  key: "e",
  keyCode: 69,
  code: "KeyE",
  which: 69,
  shiftKey: false,
  ctrlKey: false,
  metaKey: false
}));

to set more options in the object.

keyCode is the numeric code of the key that we want to set.

code has the name of the key.

which has the keyboard key number.

shiftKey sets whether we want to press the shift key in addition to the key we’re pressing.

ctrlKey sets whether we want to press the Ctrl key in addition to the key we’re pressing.

metaKey sets whether we want to press the meta key in addition to the key we’re pressing.

The meta key is the Windows key on PC keyboards and the command key on Mac keyboards.

When the event is triggered, we should see all the options logged in the addEventListener callback.

They should be in the same properties in the e object as in the options object we pass into the KeyboardEvent constructor.

We can write the same code with the keyup event.

We just replace 'keydown' with 'keyup' everywhere.

Categories
JavaScript Answers

How to Check That a Number is NaN in JavaScript?

The isNaN Function

We can use the isNaN function to check whether a number is NaN .

For instance, we can write:

const nan = isNaN(parseFloat("abc"))  
console.log(nan)

isNaN will try to parse the argument we pass into it automatically to a number.

But to be safe, we can parse it ourselves with parseFloat first to make sure we get the expected result.

We parseFloat should return NaN since we passed in a non-numeric string into it.

So isNaN should return NaN .

Therefore, nan is true .

Check Whether a Value Equals Itself

Since NaN is the only value in JavaScript which doesn’t equal itself, we can check whether a variable equals itself to check if the variable’s value is NaN .

For instance, we can write:

const nan = NaN  
console.log(nan !== nan)

Then the console log will show true since NaN doesn’t equal itself.

If nan has any other value, the console log would log false .

So if we have:

const nan = true  
console.log(nan !== nan)

Then the console log would show false .

The Number.isNaN Method

The Number.isNaN method is another method that lets us check whether a value we pass into it is NaN .

The difference between isNaN and Number.isNaN is that Number.isNaN doesn’t try to convert a value to a number before it’s checked.

For instance, we can write:

const nan = Number.isNaN('abc');  
console.log(nan)

Then console log shows false since we didn’t pass in NaN .

We just passed in something that’s not a number.

But if we write:

const nan = Number.isNaN(NaN);  
console.log(nan)

Then nan is true .

Object.is

Another method we can use to check for NaN is the Object.is method.

Object.is takes 2 arguments with the values that we want to compare.

If both values are NaN , then it returns true instead of false like we have with === .

For instance, we can write:

const a = NaN  
const nan = Object.is(a, NaN);  
console.log(nan)

Then nan is true according to the console log.

Conclusion

We can check for NaN with various functions and methods provided by JavaScript.

Also, we can use the === operator to check if a value doesn’t equal itself.

If it doesn’t, then we know the value must be NaN since NaN is the only value that doesn’t equal itself in JavaScript.