Использование текста для маскировки видео - PullRequest
0 голосов
/ 27 апреля 2018

Можно ли использовать текст HTML / CSS для маскировки видео? Я нашел и настроил такие способы работы, но ни один из них не позволяет создать прозрачный фон за текстом.

Например, эта ручка требует от вас какой-то заливки, когда она не маскирует реальное видео, а создает иллюзию.

https://codepen.io/dudleystorey/pen/QvvEYQ

Если вы измените

body {
  background: white;
  margin: 2rem;
}

К

body {
  background: black;
  margin: 2rem;
}

Вы увидите, что это просто белая заливка с маской на заливке, а не видео. Возможно, это возможно только на холсте?

1 Ответ

0 голосов
/ 27 апреля 2018

Да, вы можете легко добиться этого с помощью canvas, используя compositing и цикл рендеринга:

var vid = document.createElement('video');
vid.onerror = function() {
  vid.onerror = null;
  vid.src = "http://thenewcode.com/assets/videos/ocean-small.mp4";
};
vid.src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/ocean-small.webm"
vid.muted = true;
vid.onloadedmetadata = initCanvas;
vid.loop = true;
vid.play();

function initCanvas() {
  var canvas = document.createElement('canvas');
  var vWidth = vid.videoWidth;
  var vHeight = vid.videoHeight;
  var ctx = canvas.getContext('2d');
  // we need to handle the resizing of our canvas ourselves...
  window.onresize = function() {
    canvas.width = window.innerWidth;
    canvas.height = (vHeight / vWidth) * canvas.width;
    var fontSize = (vWidth / 2 * (window.innerWidth / vWidth)) * 0.35;
    ctx.font = '700 ' + fontSize + 'px Impact,sans-serif';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
  };
  onresize();
  
  document.body.appendChild(canvas);
  draw();
  
  function draw() {
    // first draw our video frame
    ctx.drawImage(vid, 0,0, canvas.width, canvas.height);
    // set the composite mode
    ctx.globalCompositeOperation = 'destination-in';
    // will remove every pixels that are not where new pixels will come
    ctx.fillText('OCEAN', canvas.width / 2, canvas.height / 2);
    // reset the normal compositing mode
    ctx.globalCompositeOperation = 'source-over';
    // do it again at next screen refresh
    requestAnimationFrame(draw);
  }
}
body {
  background: linear-gradient(45deg, white 0%, blue 100%) no-repeat;
}

Но это может быть не лучшим решением с точки зрения производительности и масштабируемости.

Вы должны иметь возможность применить тот же svg <mask>, который вы использовали для вашего элемента <video> (с некоторыми изменениями), но кажется, что маски SVG над содержимым HTML по-прежнему широко не поддерживаются (Firefox принимает это, Chrome не поддерживает). «т ...).

body {
  background: linear-gradient(45deg, white 0%, blue 100%);
}
svg{
  font-family: impact, sans-serif;
}
video {
  -webkit-mask: url(#mask);
  mask: url(#mask);
  width: 100%;
  position: absolute;
  z-index: 1;
}
<svg width="0" height="0" style="position:absolute;z-index:-1">
  <defs>
    <mask id="mask" x="0" y="0" maskContentUnits="objectBoundingBox" maskUnits="objectBoundingBox" width="100%" height="100%">
      <text fill="white" x="0.5" y="0.5" style="font-weight:700" font-size="0.22" text-anchor="middle" alignment-baseline="middle">OCEAN</text>
    </mask>
  </defs>
</svg>
<video autoplay playsinline muted loop preload poster="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/oceanshot.jpg">
  <source src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/ocean-small.webm" />
  <source src="http://thenewcode.com/assets/videos/ocean-small.mp4" />
</video>

Так что лучшим решением может быть использование SVG <clipPath>, который, кажется, имеет лучшую поддержку браузера, чем CSS mask.

body {
  background: linear-gradient(45deg, white 0%, blue 100%);
}
svg{
  font-family: impact, sans-serif;
}
video {
  -webkit-clip-path: url(#clip);
  clip-path: url(#clip);
  width: 100%;
  position: absolute;
  z-index: 1;
}
<svg style="opacity:0;position:fixed;z-index:-999" viewBox="0 0 1 1">
  <defs>
    <clipPath id="clip" clipPathUnits="objectBoundingBox">
      <text x="0.5" y="0.5" font-size="0.22" text-anchor="middle" alignment-baseline="middle">OCEAN</text>
    </clipPath>
  </defs>
</svg>
<video autoplay playsinline muted loop preload poster="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/oceanshot.jpg">
  <source src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/ocean-small.webm" />
  <source src="http://thenewcode.com/assets/videos/ocean-small.mp4" />
</video>

Обратите внимание, что я на самом деле не знаю поддержки браузером для css clipPath, поэтому вам, возможно, придется вернуться к canvas для некоторых браузеров.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...