//注意:不能在子组件里使用
import Taro, { Component, Config } from '@tarojs/taro'
import './index.scss'
import { View } from '@tarojs/components'
class Auth extends Component {
config: Config = {
navigationBarTitleText: 'canvas测试'
}
constructor (props) {
super(props)
this.state = {
imageTempPath:''
}
}
componentWillMount(): void {
this.drawBall()
}
drawBall() {
const context = Taro.createCanvasContext('canvas',this)
const imgPath1 = 'http://cdn.meitor.cn/meitor/main3.jpg';
const imgPath2 = 'http://cdn.meitor.cn/meitor/main3.jpg';
const _this = this;
Taro.getImageInfo({
src: imgPath1,
}).then((res)=>{
context.drawImage(res.path, 0, 0, 375, 190);
Taro.getImageInfo({
src: imgPath2,
}).then((res2)=>{
context.drawImage(res2.path, 250, 195, 86, 86);
const h= _this.fillTextWrap(context, '【润百颜玻尿酸】告别黄脸婆,一百这白丑', 20, 230, 190, 20);
context.font = 'normal 11px ArialMT sans-serif';
context.setFontSize(16);
context.setFillStyle('#FF6066');
context.fillText('¥66', 40, 290);
context.font = 'normal 11px PingFangSC-Regular sans-serif';
context.setFontSize(12);
context.setFillStyle('#FA2E9A');
context.fillText('扫描小程序码查看', 245, 300);
context.draw(false, ()=> {
Taro.canvasToTempFilePath({
canvasId: 'canvas',
success: function(res) {
// 获得图片临时路径
_this.setState({
imageTempPath:res.tempFilePath
})
}
})
});
});
});
}
saveImage(){
// 查看是否授权
Taro.getSetting({ complete(){
console.log(444)
}}).then(res=>{
if (res.authSetting['scope.writePhotosAlbum']) {
Taro.saveImageToPhotosAlbum({
filePath:this.state.imageTempPath
}).then(res=>{
console.log(res)
})
}else {
Taro.authorize({
scope: 'scope.writePhotosAlbum',
}).then(()=>{
Taro.saveImageToPhotosAlbum({
filePath:this.state.imageTempPath
}).then(res=>{
console.log(res)
})
})
}
}).catch((e)=>{
console.log(e)
})
}
// 文字换行
fillTextWrap(ctx, text, x, y, maxWidth, lineHeight) {
// 设定默认最大宽度
const systemInfo = Taro.getSystemInfoSync();
const deciveWidth = systemInfo.screenWidth;
// 默认参数
maxWidth = maxWidth || deciveWidth;
lineHeight = lineHeight || 20;
// 校验参数
if (typeof text !== 'string' || typeof x !== 'number' || typeof y !== 'number') {
return;
}
// 字符串分割为数组
const arrText = text.split('');
// 当前字符串及宽度
let currentText = '';
let currentWidth;
ctx.font = 'normal 11px sans-serif';
ctx.setFontSize(16);
ctx.setFillStyle('#3A3A3A');
ctx.setTextAlign('justify');
for (let letter of arrText) {
currentText += letter;
currentWidth = ctx.measureText(currentText).width;
if (currentWidth > maxWidth) {
ctx.fillText(currentText, x, y);
currentText = '';
y += lineHeight;
}
}
if (currentText) {
ctx.fillText(currentText, x, y);
}
}
render () {
return (
<View>
<canvas style="width: 375px; height: 320px;background:#fff" canvas-id="canvas"></canvas>
<View className='btn btn-pink save-image' onClick={this.saveImage.bind(this)}>保存图片</View>
</View>
)
}
}
export default Auth