我的代码有问题,下载的图像由 Canvas 和它上面的 div 组成,但是当我检查下载的图像时,div 的字体样式与我定义的不同。
这是Div的代码
<div id="memePlaceHolder" style="height: 700px; width:700px;background:#BBB;">
<canvas id="c" width="0" height="0">
</canvas>
<div id="myTestDiv" name="myTestDiv" >
<h1>My Test Header</h1>
<br/>
<h2>Test Text</h2>
</div>
</div>
<button onclick="save()">Save as Image</button>
这是保存函数的代码
function save() {
html2canvas(wrapperMeme, {
onrendered: function (canvasMeme) {
let a = document.createElement('a');
a.href = canvasMeme.toDataURL();
a.download = 'myImage.png';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
});
}
这是div的CSS
#myTestDiv{
font-family: 'DIN Condensed Bold';
color: #F9F3F4;
text-shadow: 0px 0px 300px #000;
padding: 1px 1px;
border: solid #F9F3F4 7px;
float:center;
width: 40%;
z-index: 2;
position: absolute;
}
最佳答案
从最初的问题来看,您似乎使用的是自定义字体,因为没有任何名为 DIN Condensed Bold 的默认字体。
如果是这种情况,则您必须使用 @font-face
规则在您的 css 中正确导入字体。
@font-face {
font-family: DIN Condensed Bold;
src: url(https://cdn.rawgit.com/justrajdeep/fonts/4b9af53d/DIN%20Condensed%20Bold.ttf);
}
ᴅᴇᴍᴏ
let wrapperMeme = document.querySelector('#memePlaceHolder');
function save() {
html2canvas(wrapperMeme, {
onrendered: function (canvasMeme) {
let a = document.createElement('a');
a.href = canvasMeme.toDataURL();
a.download = 'myImage.png';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
});
}
@font-face {
font-family: DIN Condensed Bold;
src: url(https://cdn.rawgit.com/justrajdeep/fonts/4b9af53d/DIN%20Condensed%20Bold.ttf);
}
#myTestDiv {
font-family: DIN Condensed Bold;
color: #F9F3F4;
text-shadow: 0px 0px 300px #000;
padding: 1px 1px;
border: solid #F9F3F4 7px;
float: center;
width: 40%;
z-index: 2;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<div id="memePlaceHolder" style="height: 700px; width:700px;background:#BBB;">
<canvas id="c" width="150" height="150">
</canvas>
<div id="myTestDiv" name="myTestDiv">
<h1>My Test Header</h1>
<br/>
<h2>Test Text</h2>
</div>
</div>
<button onclick="save()">Save as Image</button>
关于javascript - 下载的 Canvas 显示不同的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44040472/