终于在小程序里实现了生成字帖并下载的功能,写个文章记录一下。
1、关于字体的使用
小程序默认字体不适合书法字体,所以需要引入外部字体,这里引入楷体字体。
注意点:小程序引入字体不支持本地路径,需要使用网络路径。
1.1、引入代码
let family = 'kaiti'
let fontUrl = 'https://spkf-zsxn-prod.s3.cn-north-1.amazonaws.com.cn/pic/livecenter/kaiti.ttf'
let self = this
uni.loadFontFace({
global: true, // 是否全局生效
family: family, // 定义的字体名称
source: 'url("'+fontUrl+'")', // 字体资源的地址。格式为 TTF 和 WOFF,WOFF2 在低版本的iOS上会不兼容。
success() {
console.log('成功的回调函数')
//业务代码
}
},
fail(){
console.log('失败的回调函数')
},
complete(){
//console.log('接口调用结束的回调函数(调用成功、失败会执行)')
},
scopes: ["webview", "native"],
})
2、画格子
ctx:画布context对象,获取代码
const query = uni.createSelectorQuery()
query.select('#myCanvas')
.fields({
node: true,
size: true
})
.exec((res) => {
let canvas = res[0].node
this.canvas = canvas
this.ctx = canvas.getContext('2d')
sx:x轴开始位置
sy:y轴开始位置
w:格子宽高
drawSimpleUnreal(ctx,sx,sy,w){
let half = w / 2;
ctx.strokeStyle = '#FF0000';
ctx.lineWidth = 1;
ctx.strokeRect(sx,sy, w - 1, w - 1);
ctx.save();
ctx.lineWidth = 1;
ctx.beginPath();
ctx.setLineDash([3,3]); //创建5像素长,间隔为5像素的虚线
ctx.strokeStyle = '#e33f3f';
//横线
ctx.moveTo(sx-1, half+sy);
ctx.lineTo(w+sx-1, half+sy);
//竖线
ctx.moveTo(half+sx, sy);
ctx.lineTo(half+sx, w+sy);
ctx.stroke();
ctx.closePath();
ctx.restore();
},
drawMizige(ctx,sx,sy,w){
let half = w / 2;
ctx.strokeStyle = '#FF0000';
ctx.lineWidth = 1;
ctx.strokeRect(sx,sy, w - 1, w - 1);
ctx.save();
ctx.lineWidth = 1;
ctx.beginPath();
ctx.setLineDash([3,3]); //创建5像素长,间隔为5像素的虚线
ctx.strokeStyle = '#ec8e8e';
//横线
ctx.moveTo(sx-1, half+sy);
ctx.lineTo(w+sx-1, half+sy);
//竖线
ctx.moveTo(half+sx, sy);
ctx.lineTo(half+sx, w+sy);
//交叉线1
ctx.moveTo(sx, sy);
ctx.lineTo(sx+w, sy+w);
//交叉线2
ctx.moveTo(sx-1, sy+w);
ctx.lineTo(sx+w, sy-1);
ctx.stroke();
ctx.closePath();
ctx.restore();
},
drawTianhuige(ctx,sx,sy,w){
let half = w / 2;
ctx.strokeStyle = '#FF0000';
ctx.lineWidth = 1;
ctx.strokeRect(sx,sy, w - 1, w - 1);
ctx.save();
ctx.lineWidth = 1;
ctx.beginPath();
ctx.setLineDash([3,3]); //创建5像素长,间隔为5像素的虚线
ctx.strokeStyle = '#ec8e8e';
//横线
ctx.moveTo(sx-1, half+sy);
ctx.lineTo(w+sx-1, half+sy);
//竖线
ctx.moveTo(half+sx, sy);
ctx.lineTo(half+sx, w+sy);
//小正方形
ctx.strokeRect(sx+10,sy+10, w - 20, w - 20);
ctx.stroke();
ctx.closePath();
ctx.restore();
},
drawMihuige(ctx,sx,sy,w){
let half = w / 2;
ctx.strokeStyle = '#FF0000';
ctx.lineWidth = 1;
ctx.strokeRect(sx,sy, w - 1, w - 1);
ctx.save();
ctx.lineWidth = 1;
ctx.beginPath();
ctx.setLineDash([3,3]); //创建5像素长,间隔为5像素的虚线
ctx.strokeStyle = '#ec8e8e';
//横线
ctx.moveTo(sx-1, half+sy);
ctx.lineTo(w+sx-1, half+sy);
//竖线
ctx.moveTo(half+sx, sy);
ctx.lineTo(half+sx, w+sy);
//交叉线1
ctx.moveTo(sx, sy);
ctx.lineTo(sx+w, sy+w);
//交叉线2
ctx.moveTo(sx, sy+w);
ctx.lineTo(sx+w, sy);
//小正方形
ctx.strokeRect(sx+10,sy+10, w - 20, w - 20);
ctx.stroke();
ctx.closePath();
ctx.restore();
},
drawFangge(ctx,sx,sy,w){
let half = w / 2;
ctx.strokeStyle = '#FF0000';
ctx.lineWidth = 1;
ctx.strokeRect(sx,sy, w - 1, w - 1);
ctx.save();
ctx.stroke();
ctx.closePath();
ctx.restore();
},
3、效果图