在自己查找资料的时候看了很多博客,真正对于自己希望看的博客,或者说是便捷自己开发。
都是先放一个效果图在文章的开头,这样才能让读者知道这篇文章是否对自己有用。
先上项目中实现的效果图:
查看F12得到输出的信息:
废话不多说,上代码:(将canvas转换成 file类型)
html部分:
<canvas ref="headCanvas" style="display:none"></canvas>
js部分:
var fileName = userName + ".jpg"; //vm.addUserName
var firstName = fileName.charAt(0);
var fontSize = 60;
var fontWeight = 'bold';
var canvas = this.$refs.headCanvas;
//var canvas = document.getElementById('headImg');
canvas.width = 120;
canvas.height = 120;
var context = canvas.getContext('2d');
context.fillStyle = '#F7F7F9';
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = '#605CA8';
context.font = fontWeight + ' ' + fontSize + 'px sans-serif';
context.textAlign = 'center';
context.textBaseline="middle";
context.fillText(firstName, fontSize, fontSize);
var dataurl = canvas.toDataURL("image/png");
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
var file = new File([u8arr], fileName, {type: mime});
file.lastModifiedDate = new Date();
console.info(file);
这样就能达到效果图了。。