js使用Canvas將多張圖片合并成一張的實(shí)現(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將多張圖片合并成一張的實(shí)現(xiàn)代碼的文章就介紹到這了,更多相關(guān)js canvas圖片合并一張內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Spring security 自定義過濾器實(shí)現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實(shí)例代碼)2. Java8內(nèi)存模型PermGen Metaspace實(shí)例解析3. python wsgiref源碼解析4. 一文搞懂 parseInt()函數(shù)異常行為5. python tkinter實(shí)現(xiàn)下載進(jìn)度條及抖音視頻去水印原理6. python學(xué)習(xí)之plot函數(shù)的使用教程7. python 實(shí)現(xiàn)關(guān)聯(lián)規(guī)則算法Apriori的示例8. ASP.NET MVC使用正則表達(dá)式驗(yàn)證手機(jī)號(hào)碼9. Python基于百度AI實(shí)現(xiàn)抓取表情包10. python 實(shí)現(xiàn)"神經(jīng)衰弱"翻牌游戲
