html2canvas是一個將html元素生成canvas的庫,繪製的canvas大部分樣式和CSS一致。好比截止1.0.0-alpha.12,虛線邊框依然繪製爲實線,border-collapse依然有問題。html
這裏根據github issues裏的一個思路,模擬實現了dashed邊框效果。git
適用狀況:單獨邊框較多,即不是完整邊框,同時不考慮border-radiusgithub
findDashedBorders = (page) => { const tds = page.querySelectorAll("td"); const borders = []; tds.forEach(td => { const computedStyle = window.getComputedStyle(td); const borderStyle = computedStyle.borderStyle ? computedStyle.borderStyle.split(' ') : []; const dashedIndex = findAll(borderStyle, 'dashed'); if (dashedIndex.length) { const rect = td.getBoundingClientRect(); dashedIndex.map(index => { const border = { rect, border: dashedBorder[index] } borders.push(border); td.style[`border${dashedBorder[index]}Color`] = 'transparent'; }); } }); return borders; }
page是須要繪製canvas的元素,我這裏有dashed邊框的都是td元素,因此查找全部td元素,使用getComputedStyle()方法查找它的borderStyle,若是它有dashed邊框,那麼這個屬性的值的形式爲"dashed dashed none none",因此根據findAll()這個自定義方法找到全部的dashed的方向(好比"dashed dashed none none"將返回[0, 1]),其中dashedBorder數組以下:chrome
const dashedBorder = ["Top", "Right", "Bottom", "Left"];
找到方位後同時獲取它的位置,將方向和位置信息存入borders數組,同時將這條邊框設爲透明,使html2canvas不繪製這條框,咱們以後會單獨處理。(注意:這個頁面的虛線邊框都會透明掉,這裏並無考慮繪製完成後將透明邊框變回原來的顏色)canvas
pages.forEach((page, idx) => { const borders = this.findDashedBorders(page); const parentRect = page.getBoundingClientRect(); html2canvas(page, {scale: 2, logging: false, useCORS: true}).then((canvas) => { this.drawDashedBorder(canvas, borders, parentRect); ...... }) })
pages是須要繪製canvas的全部元素,咱們在獲取每一個page的虛線邊框時,同時獲取這個page的位置,以便咱們繪製dashed邊框時獲得邊框相對於這個頁面的位置。待html2canvas繪製canvas後,咱們經過drawDashedBorder()方法進一步繪製出dashed邊框,下面實現這個方法。數組
drawDashedBorder = (canvas, borders, parentRect) => { var ctx = canvas.getContext("2d"); ctx.setLineDash([6, 3]); ctx.strokeStyle = '#3089c7'; ctx.lineWidth = 1; ctx.globalAlpha = 1; borders.forEach(border => { var left = (border.rect.left + 0.5 - parentRect.left)*2; var right = (border.rect.right - 0.5 - parentRect.left)*2; var top = (border.rect.top + 0.5 - parentRect.top)*2; var bottom = (border.rect.bottom - 0.5 - parentRect.top)*2; switch (border.border) { case 'Top': ctx.beginPath(); ctx.moveTo(left, top); ctx.lineTo(right, top); ctx.stroke(); break; case 'Right': ctx.beginPath(); ctx.moveTo(right, top); ctx.lineTo(right, bottom); ctx.stroke(); break; case 'Bottom': ctx.beginPath(); ctx.moveTo(left, bottom); ctx.lineTo(right, bottom); ctx.stroke(); break; case 'Left': ctx.beginPath(); ctx.moveTo(left, top); ctx.lineTo(left, bottom); ctx.stroke(); break; default: break; } }) }
意思就是根據borders裏dashed邊框的方向和位置信息,在canvas裏獲取2d上下文後使用setLineDash方法把虛線繪製出來。位置都*2是由於咱們以前canvas使用了2倍大小。測試
因爲對canvas理解不深沒法pr,只能期待html2canvas的官方實現了。this