js使用Canvas將多張圖片合并成一張的實現(xiàn)代碼
解決方案
function mergeImgs(list) { const imgDom = document.createElement(’img’) document.body.appendChild(imgDom) const canvas = document.createElement(’canvas’) canvas.width = 500 canvas.height = 500 * list.length const context = canvas.getContext(’2d’) list.map((item, index) => { const img = new Image() img.src = item // 跨域 img.crossOrigin = ’Anonymous’ img.onload = () => { context.drawImage(img, 0, 500 * index, 500, 500) const base64 = canvas.toDataURL(’image/png’) imgDom.setAttribute(’src’, base64) // console.log(baseList) } })}const urlList = [’./img/timg%20(1).jpg’, ’./img/timg.jpg’]mergeImgs(urlList )
代碼稍微優(yōu)化一下,改成公共方法
/** * 合并多張圖片,返回新的圖片 * @param {Array} list 圖片url數(shù)組 * @param {Number} cwith 畫布寬度 默認(rèn)500 * @param {Number} cheight 畫布高度 默認(rèn)500 */function mergeImgs(list, cwith = 500, cheight = 500) { return new Promise((resolve, reject) => { const baseList = [] const canvas = document.createElement(’canvas’) canvas.width = cwith canvas.height = cheight * list.length const context = canvas.getContext(’2d’) list.map((item, index) => { const img = new Image() img.src = item // 跨域 img.crossOrigin = ’Anonymous’ img.onload = () => { context.drawImage(img, 0, cheight * index, cwith, cheight) const base64 = canvas.toDataURL(’image/png’) baseList.push(base64) if (baseList[list.length - 1]) { console.log(baseList) // 返回新的圖片 resolve(baseList[list.length - 1]) } } }) })}const urlList = [’./img/timg%20(1).jpg’, ’./img/timg.jpg’]mergeImgs(urlList ).then(base64 => {const imgDom = document.createElement(’img’)imgDom.src = base64document.body.appendChild(imgDom)})
效果
到此這篇關(guān)于js使用Canvas將多張圖片合并成一張的實現(xiàn)代碼的文章就介紹到這了,更多相關(guān)js canvas圖片合并一張內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析2. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析3. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp4. SharePoint Server 2019新特性介紹5. ASP中常用的22個FSO文件操作函數(shù)整理6. React+umi+typeScript創(chuàng)建項目的過程7. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究8. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁9. 三個不常見的 HTML5 實用新特性簡介10. php測試程序運行速度和頁面執(zhí)行速度的代碼
