小弟打算用 html2canvas 将网页中的 DOM 元素转成图片,当作海报用。
想限制 canvas 的尺寸在 750 * 1334,于是在网页上设置个 canvas 节点。
<canvas id="myCanvas" width=750 height=1334></canvas>
然后 js 里面这么写:
var options = {
canvas: document.querySelector('#myCanvas'),
}
html2canvas(document.querySelector("sel"), options).then(canvas => {
document.body.appendChild(canvas)
});
这样导致生成的 canvas 有个 style 行内样式,里面的宽高和 DOM 大小相关。
后来看了文档,把 option 对象里增加了 width 和 height ,也没用。
后面又尝试在回调函数里把 style.width 和 style.height 设置为空,这样有效,但是 canvas 本身的宽高又变了,比如这样(先用代码表示下,小弟明天截图)
<canvas width="不是750" height="不是1334"></canvas>
在此请教下各位,如何限制生成的 canvas 宽高固定不变?谢谢各位。
更新下问题:我的 dom 元素是 285 449,传入 options 对象将 scale 设置为 2,并且设置 canvas 为页面上的 750 1334 的 canvas,在回调函数里将canvas 的 style 的宽高设置为空。如下:
let cfg = {
canvas: document.querySelector('#myCanvas'),
scale: 2,
}
html2canvas(document.querySelector(".main"), cfg).then(canvas => {
canvas.style.width = null
canvas.style.height = null
});
})
最后生成的 canvas 如下:
<canvas id="myCanvas" width="570" height="898" style=""></canvas>
请教下如何固定 canvas 的宽高?谢谢。