Skip to content

Let's make a Picture in Picture Countdown timer on the Web

Caution: This currently works only on Chrome and Safari. Firefox still does not have support for programmatic PiP.

Can I Use - Picture in Picture

The Normal Pomodoro Timer

I'm starting off with a normal countdown pomodoro timer. I will be using AlpineJS. For the uninitiated, AlpineJS is a small JavaScript library that uses Vue/Angular like syntax to bring reactivity to the DOM. If you are familiar with Vue or Angular, then you should feel right at home with the syntax.

<main x-data="timer()" x-init="init()">
    <p x-text="text"></p>
  <div class="button-container">
      x-text='interval ? "Pause" : "Start"'
      @click="interval ? pause() : start()"
    <button @click="stop()">Reset</button>


const zeroPad = (num, places) => String(num).padStart(places, '0');

const formatTime({minutes, seconds}) = () => `${zeroPad(minutes, 2)} : ${zeroPad(seconds, 2)}`;

function timer() {
  return {
    interval: null,
    text: '',
    time: {
      minutes: 25,
      seconds: 0,
    init() {
      this.text = formatTime(this.time);
    start() {
      this.interval = setInterval(() => {
        const time = calculateTime(this.time);
        this.time = time;
        if(time.minutes === 0 && time.seconds === 0) {
        this.text = formatTime(time);
      }, 1000);
    stop() {
      this.interval = null;
      this.time = {
        minutes: 25,
        seconds: 0,
      this.text = formatTime(this.time);
    pause() {
      this.interval = null;

You need AlpineJS needed for this. You can load it from a CDN

Picture in Picture

As a sidenote, let us talk about Picture in Picture (This is where we are going at the end, but still).

Google Developers pages have some great tutorials on picture in picture.

But by essence, you can request a video to play picture in picture with:

const videoEl = document.querySelector("#video");

You can see if a device supports Picture in Picture with:

if (!("pictureInPictureEnabled" in document)) {
  console.log("The Picture-in-Picture Web API is not available.");
} else if (!document.pictureInPictureEnabled) {
  console.log("The Picture-in-Picture Web API is disabled.");

Bringing Canvas into the Picture

How do we bring the canvas into this? Well, Chrome allows for any video to play Picture in Picture and luckily for us, Canvas comes with a captureStream API that allows us to capture any stream on a canvas and capture it on video all in real time.

Here is how we would do that:

const canvas = document.createElement("canvas");
// Draw something to canvas.
canvas.getContext("2d").fillRect(0, 0, canvas.width, canvas.height);

const video = document.createElement("video");
video.muted = true;
video.srcObject = canvas.captureStream();;

All Together now