<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>如何将Canvas绘制过程转为视频</title> <style> html, body { width: 100%; height: 100%; } .main { display: flex; } #videoContainer { display: none; } </style> </head> <body> <div class="main"> <canvas width="600" height='600'></canvas> <div id="videoContainer"> <h2>视频</h2> <video width='300' height='300' controls='true' autoplay='true' id='video'></video> </div> </div> </body> <script> const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); // const {width, height}= canvas; const width = canvas.width; const height = canvas.height; ctx.fillStyle = 'red'; function draw(rotation = 0){ // save()表示保存save函数之前的状态,restore()表示获取save函数保存的状态 // save()与restore()之间的程序并不影响restore()之后的程序 ctx.clearRect(0, 0, 1000, 1000); ctx.save(); ctx.translate(width/ 2, height/ 2); ctx.rotate(rotation); ctx.translate(-width/ 2, -height/ 2); // beginPath() 方法开始一条路径,或重置当前的路径。 ctx.beginPath(); ctx.rect(200, 200, 200, 200); ctx.fill(); ctx.restore(); } (function update(t){ draw(t/ 500); // 在浏览器下次重绘之前继续更新下一帧动画 // 那么回调函数自身必须再次调用window.requestAnimationFrame() requestAnimationFrame(update); })(0); const stream = canvas.captureStream(); const recorder = new MediaRecorder(stream, {mimeType: 'video/webm'}); const data = []; recorder.ondataavailable = function(event){ if(event.data && event.data.size) { data.push(event.data); } } recorder.onstop = ()=>{ const url = URL.createObjectURL( new Blob(data, {type:'video/webm'}) ); document.querySelector("#videoContainer").style.display = "block"; document.querySelector("video").src = url; }; recorder.start(); setTimeout(()=>{ recorder.stop(); },6000); </script> </html>