JavaScript ビデオを撮影 スクリーンショット スナップショット
スクショ後、ブラウザのダウンロードフォルダに画像をダウンロード
var canvas = document.createElement('canvas'); var video = document.querySelector('video'); var ctx = canvas.getContext('2d'); // Change the size here canvas.width = parseInt(video.offsetWidth); canvas.height = parseInt(video.offsetHeight); ctx.drawImage(video, 0, 0, canvas.width, canvas.height); var a = document.createElement('a'); a.download = 'snap-' + canvas.width + 'x' + canvas.height + '-' + video.currentTime + '.jpg'; // Won't work on file:/// URLs. SecurityError: Tainted canvases may not be exported. a.href = canvas.toDataURL('image/jpeg'); document.body.appendChild(a).click(); a.remove();
スクショ後、別タブで画像を開く&画像クリックでブラウザのダウンロードフォルダにDL
var canvas = document.createElement('canvas'); var video = document.querySelector('video'); var ctx = canvas.getContext('2d'); // Change the size here canvas.width = parseInt(video.offsetWidth); canvas.height = parseInt(video.offsetHeight); ctx.drawImage(video, 0, 0, canvas.width, canvas.height); // Won't work on file:/// URLs. SecurityError: Tainted canvases may not be exported. var base64ImageData = canvas.toDataURL('image/jpeg'); var filename = 'snap-' + canvas.width + 'x' + canvas.height + '-' + video.currentTime + '.jpg'; // Wrap <img> in link to download image because // the context menu Save Image as... is blocked for security reasons var a = document.createElement('a'); a.download = filename; a.href = base64ImageData; var img = document.createElement('img'); img.src = base64ImageData; img.alt = filename; img.title = 'Click to save ' + filename; window.open().document.body.appendChild(a).appendChild(img);
iOS対応を考慮する場合は、querySelector('video');ではなく下記のように書くこと。
let video = ifrm.getElementsByClassName('video__media')[0];
この書き方をしておけばiOSでも非iOSでもOKなので、とりあえずこちらで書くのがよさそう。
参考
https://github.com/ReeganExE/youtube-screenshot/blob/master/youtube-screengrab.js
https://github.com/ReeganExE/youtube-screenshot/blob/master/youtube-screenshot.js
注意
canvasオブジェクトは、document上でcreateするだけでは画面上に表示されないため、
デザイン崩れ・見え方異常などは発生しない。
(表示するにはappendChildでノードに登録する必要がある)