HTML5 圖表( ?° ?? ?°)如何畫(huà)視頻
(圖片來(lái)源網(wǎng)絡(luò ),圖表侵刪)在 HTML5 中,何畫(huà)我們可以??使用 &??lt;canvas> 元素和 JavaScript 來(lái)繪制圖表,視頻以下是圖表一個(gè)簡(jiǎn)單的步驟說(shuō)明:
1、創(chuàng )建 <canvas> 元素
2、何畫(huà)獲取 canv??as 上下文
3、視頻繪制圖表
4、(′?_?`)圖表將圖表轉換為視頻
1. 創(chuàng )建 <canvas> 元素
在 HTML 文件中創(chuàng )建一個(gè) <canva?s> 元素,何畫(huà)并設置寬度和高度。視頻
<!DOCTYPE html><html><head> <meta charset="utf8&quo??(?⊿?)t;> <title>HTML5 圖表繪制</title><???/head><body> <canvas id="myCanvas" width="600( ?ヮ?)" height="400"></canvas> <scrip?t src=ヽ(′▽?zhuān)?ノ&quo??t;chart.js&qu??ot;></script></body></html>
2. 獲取 canvas 上下文
接下來(lái),圖表我們需要獲取 canvas 的何畫(huà)上下文,以便在其上繪制圖形,視頻在 JavaScript?? 文件中,圖表可以使用以下代碼:
const canvas = document.getEl??ementById('myCanvas');const ctx = canvas.getContext('2d');現在我們可以開(kāi)始繪制圖表了,何畫(huà)以下是視頻一個(gè)簡(jiǎn)單的折線(xiàn)圖示例:
// 繪制坐標軸ctx.beginPath();ctx.moveTo(50, 200);ctx.lineTo(550, 200);ctx.stroke();ctx.beginPath();ctx.moveTo(300, 50);ctx.lineTo(ヽ(′ー`)ノ300, 350);ctx.?stroke();// 繪制數據點(diǎn)con(??ヮ?)?*:???st data = [100, 150, 200, 150, 100];const maxValue = Math.max(...data);const minVal(╬ ò﹏ó)ue = Ma(′_ゝ`)th.min(...dat???a);f??or (let i = 0; i < data.length; i++) { const x = 50 + i * (550 50) / data.length; const y = 350 (data[i] minValue) * (350 50) / (maxValue minValue); ctx.beginPath(); ctx.arc(x, y, 5, 0, 2 * Math.PI); ctx.fill()??;}// 連接數據點(diǎn)ctx??.beginPath();ctx.moveTo(50 + data[0] * (550 50) / data.ヾ(?■_■)ノlength, 350 (data[0] minValue) * (350 50) / (maxValue minValue));for (let i = 1; i < data.le??ngth; i++) { ctx.lineTo(50 + data[i] * (550 50) / data.length, 350 (da(?Д?)ta[i] minValue) * (350 50) / (max(???)Value(?⊿?) minValue));}ctx??.stroke();4. 將圖表轉換為視頻
要將繪制的圖表轉換為視頻,我們需要使用第三方庫,ffmpeg.js,將其添加到項目中:
&l(′_ゝ`)t;script src="https://cdnjs??.cloudflare.com/a??jax/libs/ffmpeg.js/3.1.9008/ffmpeg.min.js"></script>
使用以下代碼將 canvas 轉(zhuan)換為視頻:
async function canvasToVideo(canvas, outputFormat, outputFilename) { const dataURI = canvas.toDataURL('image/png'); const ffmpeg = createFFMPEG({ log: true }); await ffmpeg.load(); const inputStream = ffmpeg.createInputStream({ file: dataURI, options: 'f image2pipe vcodec mjpeg', pix_fmt: 'yuv420p', lo(′_`)glevel: 'quiet', format: 'image2pipe', stream_??id: 'input' }); const outputOptions = f ${(′?_?`) outputFormat} vcodec libx264 pix_fmt yuv420p r 30 b:v 1M preset ultrafast tune zerolatency profile:v baseline s 640x480 i pipe:input=inputStream f ${ outputFormat}?? y ${ outputFヽ(′▽?zhuān)?ノilename}; const outputStream = ffmpeg.createOutputStream({ options: outputOptions }); await new Promise((resolve, reject) => { ffmpeg.ru??n(inputStream, outputStream, (err, stats) => { if (err) { reject(err); } else { resolve(stats); } }); });}canvasToVid(′▽?zhuān)?eo(canvas, 'mp4', 'chart.mp4');