生成前端海報(bào)的 N 種方案和優(yōu)劣

點(diǎn)擊上方 前端瓶子君,關(guān)注公眾號(hào)
回復(fù)算法,加入前端編程面試算法每日一題群
一、背景
工作中做了很多生成海報(bào)的功能,不同需求,不同場(chǎng)景,使用了幾種方案,各有優(yōu)劣。一直想要整理一下,但這個(gè)過(guò)程中的思考和遇到的問(wèn)題沒(méi)有記錄下來(lái),比如圖片的跨域問(wèn)題,文字的問(wèn)題,做完沒(méi)有記錄,無(wú)跡可尋,以至于很難開(kāi)始。最近重新回顧了一下,整理了一篇文檔,或有疏漏和不準(zhǔn)確之處,歡迎交流。
二、業(yè)務(wù)應(yīng)用
pc:
1.分享海報(bào)
H5應(yīng)用:
1.分享優(yōu)惠券
2.年度賬單
3.分享海報(bào)
三、實(shí)現(xiàn)方式及兼容性問(wèn)題
第三方庫(kù)
1. html2canvas
版本 1.0.0rc7
https://github.com/niklasvh/h...
star:22k
時(shí)間 2021-01-06
首頁(yè)測(cè)試demo:https://html2canvas.hertzen.com/
兼容性測(cè)試
安卓
-
? 6.0 koobee -
? 5.0.2 vovoY51A
安卓微信版本-內(nèi)置
-
? 7.0.3 -
? 7.0.22
ios
-
? 14.2 -
? 11.2.1
ios微信內(nèi)置
-
? 7.0.20 -
? 7.0.1
優(yōu)點(diǎn):
兼容性更好,官方描述如下:
Browser compatibility
The library should work fine on the following browsers (with Promise polyfill):
Firefox 3.5+
Google Chrome
Opera 12+
IE9+
Safari 6+
As each CSS property needs to be manually built to be supported, there are a number of properties that are not yet supported.
缺點(diǎn):
一些屬性不支持轉(zhuǎn)化:如不支持偽類(lèi),border不支持dash,不支持text-shadow,(即還原程度需要和設(shè)計(jì)溝通,或者考慮采用圖片等形式去替換顯示元素)
features:https://html2canvas.hertzen.c...
備注
rc5出現(xiàn)過(guò)ios生成不了圖片的問(wèn)題,還原到rc4就可以了
https://github.com/niklasvh/h...
看到issue里有出現(xiàn)ios某些版本下微信失敗的情況,暫沒(méi)有復(fù)現(xiàn)
2 dom-to-img
版本2.6.0
https://github.com/tsayen/dom...
star:6.9k
優(yōu)點(diǎn)
元素齊全,還原度高
缺點(diǎn)
不兼容safari,所以建議只在Chrome下使用
沒(méi)有維護(hù)更新了
兼容性問(wèn)題
1.作者明確表示不支持safari,因?yàn)閒oreignObject的安全性問(wèn)題(明說(shuō)了不支持,我仔細(xì)看文檔 => 白作工 )

鏈接:
-
https://github.com/tsayen/dom... -
https://html.spec.whatwg.org/... -
SVG在Web攻擊中的應(yīng)用: https://www.anquanke.com/post...
2.iOS14.2下,圖片丟失問(wèn)題
其實(shí)在測(cè)的時(shí)候,發(fā)現(xiàn)ios14.2下生成圖片第一次始終會(huì)出現(xiàn)圖片丟失,第二次或第三次正常
解決方案,2~3次調(diào)用,取最后一次(看issue里有些機(jī)型還是不支持的)
3.低端安卓機(jī)上會(huì)出現(xiàn)失敗情況,主要是文字的問(wèn)題(這里是我寫(xiě)過(guò)的舊的記錄,不是很確定)
應(yīng)用于Pc或android
-
清晰度問(wèn)題:\(看到很多人說(shuō)要去改源碼,其實(shí)不用的,作者是提供了參數(shù)了\)
通過(guò)scale放大設(shè)備的DPR倍數(shù)
let elm = document.getElementById('my-node')
const scale = window.devicePixelRatio
this.loader.open()
await this.$nextTick()
domtoimage
.toBlob(elm, {
quantity: 1,
width: elm.offsetWidth * scale, // 畫(huà)布放大
height: elm.offsetHeight * scale,
style: {
transform: `scale(${scale})`, // 元素放大
transformOrigin: '0 0',
},
})
.then(this.upload) // 處理結(jié)果
.catch(function (error) {
this.loader.close()
console.error('oops, something went wrong!', error)
})
前端canvas繪制
0.canvas
let canvasBox = document.createElement('canvas')
let ctx = canvasBox.getContext(
'2d'
) as CanvasRenderingContext2D
1.img
let bgImag = ''
ctx.drawImage(bgImg, 0, 0)
1.2圖片跨域問(wèn)題
解決辦法 :
1)使用 crossOrigin 屬性。
解決canvas圖片getImageData,toDataURL跨域問(wèn)題
2)圖片本身也需要允許跨域
3)設(shè)置 useCORS:true,原理相同,但使用以上跨域方法,若同時(shí)設(shè)置為 allowTaint:true ,仍然會(huì)認(rèn)為畫(huà)布已被污染而不可用;
2.文字
2.2文字換行
核心:計(jì)算所有文字,根據(jù)每行可顯示的最大寬度,來(lái)拆分成每行渲染
參考:https://www.zhangxinxu.com/wordpress/2018/02/canvas-text-break-line-letter-spacing-vertical/
2.2字體類(lèi)型
2.2.1.只采用默認(rèn)字體或少量定制字體(Fontmin獲取特定字體的字體,寫(xiě)死的數(shù)據(jù),如果換行需要計(jì)算換行問(wèn)題-空格回車(chē)等奇葩問(wèn)題)- ==@font-face,這樣使用是涉及版權(quán)問(wèn)題的,確保你們有該字體的版權(quán)==
@font-face {
font-family: "DIN Condensed";
// prettier-ignore
src: url("~@/assets/fonts/DIN-Condensed-Bold.woff") format("woff"), url("~@/assets/fonts/DIN-Condensed-Bold.ttf") format("ttf");
}
@font-face {
font-family: "PingFang SC Bold";
// prettier-ignore
src: url("~@/assets/fonts/PingFang-SC-Bold.ttf") format("ttf"), url("~@/assets/fonts/PingFang-SC-Bold.woff") format("woff");
}
ctx.fillText('20px PingFang SC Bold', x, y)
ctx.fillText('20px', x, y)
2.2.2(一定要完整某種字體的情況下:動(dòng)態(tài)變化的數(shù)據(jù),需要接口支持)
svg to img
直接domtoSvg也有安卓失敗的問(wèn)題
let svg = 接口獲取svg(參考年度賬單)
let svgBase64: string =
'data:image/svg+xml;base64,' +
window.btoa(
unescape(encodeURIComponent(svg))
)
await this.loadImg(svgBase64).then(
img => {
ctxC.drawImage(
img,
~~(20 * this.scale),
~~(186 * this.scale)
)
}
)
3.手機(jī)端比例計(jì)算
// 盡量使用整數(shù)
// devicePixelRatio
protected imgQuality = window.devicePixelRatio
// 和設(shè)計(jì)稿的比例 設(shè)計(jì)稿寬度是640
get scale() {
return (document.body.clientWidth * this.imgQuality) / 640
}
// 畫(huà)布寬高,避免生成的圖片模糊情況出現(xiàn)
canvasBox.width = Math.ceil(
document.body.clientWidth * this.imgQuality
)
canvasBox.height = Math.ceil(980 * this.scale)
// 二維碼的寬度
get qrCodeSize() {
return ~~(155 * this.scale) // rpx * scale
}
4.常見(jiàn)元素/線/圓/圓角矩形
// 畫(huà)布和設(shè)計(jì)稿750的比例
scale = (document.body.clientWidth * this.imgQuality) / 750
線:
**
* 畫(huà)線
*/
export function drawLine(
ctx: CanvasRenderingContext2D,
data: {
x: number
y: number
width: number
height: number
strokeStyle: string
},
scale: number
) {
let x = data.x * scale
let y = data.y * scale
let dx = (data.x + data.width) * scale
let dy = data.y * scale
// 開(kāi)始一個(gè)新的繪制路徑
ctx.beginPath()
// 定義直線的起點(diǎn)坐標(biāo)為(10,10)
ctx.moveTo(x, y)
// 定義直線的終點(diǎn)坐標(biāo)為(50,10)
ctx.lineTo(dx, dy)
// 顏色
ctx.strokeStyle = data.strokeStyle
// 沿著坐標(biāo)點(diǎn)順序的路徑繪制直線
ctx.stroke()
// 關(guān)閉當(dāng)前的繪制路徑
ctx.closePath()
}
圓:
/**
* 畫(huà)圓
*/
export function drawCircle(
ctx: CanvasRenderingContext2D,
data: {
x: number // 圓心
y: number
size: number // 半徑
fillStyle: string
},
scale: number
) {
ctx.save()
ctx.beginPath()
ctx.arc(
~~(data.x * scale),
~~(data.y * scale),
~~(data.size * scale),
0,
~~(data.size * scale * Math.PI)
)
ctx.fillStyle = data.fillStyle
ctx.fill()
ctx.restore()
}
矩形:
/**
* 畫(huà)圓角矩形
*/
export function drawRoundRect(
ctx: CanvasRenderingContext2D,
data: {
x: number
y: number
width: number
height: number
radius: number
fillStyle: string
},
scale: number
) {
let width = ~~(data.width * scale)
let height = ~~(data.height * scale)
let radius = ~~(data.radius * scale)
let fillStyle = data.fillStyle
ctx.save()
ctx.translate(~~(data.x * scale), ~~(data.y * scale))
ctx.beginPath()
// 從右下角順時(shí)針繪制,弧度從0到1/2PI
ctx.arc(width - radius, height - radius, radius, 0, Math.PI / 2)
// 矩形下邊線
ctx.lineTo(radius, height)
// 左下角圓弧,弧度從1/2PI到PI
ctx.arc(radius, height - radius, radius, Math.PI / 2, Math.PI)
// 矩形左邊線
ctx.lineTo(0, radius)
// 左上角圓弧,弧度從PI到3/2PI
ctx.arc(radius, radius, radius, Math.PI, (Math.PI * 3) / 2)
// 上邊線
ctx.lineTo(width - radius, 0)
// 右上角圓弧
ctx.arc(width - radius, radius, radius, (Math.PI * 3) / 2, Math.PI * 2)
// 右邊線
ctx.lineTo(width, height - radius)
ctx.closePath()
ctx.fillStyle = fillStyle
ctx.fill()
ctx.restore()
}
5.canvasBox.toBlob
canvasBox.toBlob(async data => {
if (data) {
//上傳到7niu
this.url = await uploadFile(data)
}
})
6.圖片保存
PC
import { saveAs } from 'file-saver'
saveAs(blob, filename)
H5
長(zhǎng)按保存
包殼的H5是可以實(shí)現(xiàn)直接下載的,但為了交互了一致性,還是用了長(zhǎng)按
接口生成
接口生成,傳入元素和位置等信息,接口直接生成返回圖片。需要后端實(shí)現(xiàn)。(具體的性能和使用案例,歡迎討論。)
優(yōu)點(diǎn)
不需要考慮兼容性等問(wèn)題
缺點(diǎn)
不支持字?jǐn)?shù)或字體類(lèi)型過(guò)多,服務(wù)器壓力較大(看具體實(shí)現(xiàn)方案),元素越多,接口越慢
這個(gè)方案其實(shí)也是用后端的邏輯實(shí)現(xiàn)了繪制元素,輸出圖片(過(guò)程中遇到的問(wèn)題:如換行情況下需要計(jì)算字體高度(同一字體的中英文寬度不同)和后續(xù)元素的相對(duì)位置發(fā)生變化)
四、圖片跨域
如果存在跨域圖片無(wú)法下載,仔細(xì)閱讀以下文字:
來(lái)源:https://segmentfault.com/q/10...
五、總結(jié)
無(wú)特殊情況時(shí),pc下使用dom-to-image即可。
至于h5,回顧了一下自己繪制海報(bào)的實(shí)現(xiàn)歷程:
1.第三方庫(kù)(兼容性問(wèn)題,太久遠(yuǎn)以至于不記得發(fā)生了什么,只記得這個(gè)方案被駁回了)
2.接口繪制(服務(wù)器過(guò)載性能問(wèn)題,速度過(guò)慢)
3.前端canvas繪制(+部分元素接口繪制好返回圖片或svg,基本沒(méi)什么兼容問(wèn)題)(速度過(guò)慢)
4.第三方庫(kù)(html2canvas,測(cè)試了一些版本環(huán)境的兼容性,但項(xiàng)目暫未上線,需要觀察)
目前最優(yōu)解看起來(lái)是html2canvas,但是有些效果無(wú)法實(shí)現(xiàn),需要在還原度和性能上做取舍。
六、更好的方案?
一些常用的app的海報(bào)生成是更快的,體驗(yàn)也更好,不知道是不是存在更好的解決方案?還是h5的限制?
七、參考
-
【JS】節(jié)點(diǎn)截圖的最終解決方案dom-to-image與html2canvas:https://blog.csdn.net/Mcky_Lo... -
移動(dòng)端H5頁(yè)面截圖:https://cloud.tencent.com/dev... -
把DOM節(jié)點(diǎn)生成base64圖片:https://www.jianshu.com/p/c5c... -
更優(yōu)雅地基于 canvas 在前端畫(huà)海報(bào):https://juejin.cn/post/684490... -
canvas文本繪制自動(dòng)換行、字間距、豎排等實(shí)現(xiàn) https://www.zhangxinxu.com/wo... -
圖片跨域問(wèn)題:https://segmentfault.com/q/1010000008648867
來(lái)自:SegmentFault,作者:JiaXinYi
鏈接:https://segmentfault.com/a/1190000038910770
