<template>
<view class='page'>
<canvas canvas-id="myCanvas" id='sss' mode="widthFix"></canvas>
<image :src="base64" mode="" v-if="base64" class='immm' mode="widthFix"></image>
<button type="primary" @click='bcFn' v-if="base64" >保存图片</button>
</view>
</template>
<script>
export default {
data() {
return {
text: '',
base64:null
}
},
onLoad() {
this.copyFn()
},
methods: {
copyFn() {
uni.showLoading({ //增加loading等待效果
mask:true,
})
let ww, hh;
// let
const query = uni.createSelectorQuery().in(this);
query.select('#sss').boundingClientRect(data => { //获取canvas-dom
ww = data.width; //准确的宽高
hh = data.height
var ctx = uni.createCanvasContext('myCanvas') //绑定画布
ctx.drawImage('../../static/poster/beijin.jpg', 0, 0, ww, hh); //填充进图片
ctx.drawImage(uni.getStorageSync("carListItem").carListSrc, ww*0.18, hh*0.175, ww*0.64, hh*0.31); //填充进图片
// 圆角矩形
// let x=0,y=0,w=ww*0.8,h=hh*0.8,r=10
// let x=ww*0.1,y=hh*0.1,w=ww*0.8,h=hh*0.8,r=10
// ctx.beginPath()
// // 因为边缘描边存在锯齿,最好指定使用 transparent 填充
// ctx.setFillStyle('transparent')
// // ctx.setStrokeStyle('transparent')
// // 左上角
// // ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
// ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 2.5)
// // border-top
// ctx.moveTo(x + r, y)
// ctx.lineTo(x + w - r, y)
// ctx.lineTo(x + w, y + r)
// // 右上角
// ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
// // border-right
// ctx.lineTo(x + w, y + h - r)
// ctx.lineTo(x + w - r, y + h)
// // 右下角
// ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
// // border-bottom
// ctx.lineTo(x + r, y + h)
// ctx.lineTo(x, y + h - r)
// // 左下角
// ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
// // border-left
// ctx.lineTo(x, y + r)
// ctx.lineTo(x + r, y)
// // 这里是使用 fill 还是 stroke都可以,二选一即可,但是需要与上面对应
// ctx.fill()
// // ctx.stroke()
// ctx.closePath()
// // 剪切
// ctx.clip()
// ctx.setFillStyle('#ffffff')
// ctx.fillRect(ww*0.1,hh*0.1, ww*0.85, hh*0.85)
//
ctx.setFillStyle('#000') //设置内容1的文字样式
ctx.setFontSize(14);
ctx.setTextAlign('center') //设置对于坐标点的对齐方式
ctx.fillText("大众一汽-大众宝来2012款 1.4T 自动 舒适型",ww/2,hh/2+55) //计算距离,将文字定位于图片的某处
ctx.setFillStyle('red') //设置内容2的文字样式
ctx.setFontSize(14);
ctx.setTextAlign('center') //同上
ctx.fillText('我就试试的萨芬萨芬',ww/2,hh/2+80)
// ctx.drawImage('../../static/ico/chexian.png', 100, 100, ww, hh); //填充进图片
ctx.draw(); //输出到画布中
setTimeout(()=>{ //不加延迟的话,base64有时候会赋予undefined
uni.canvasToTempFilePath({
canvasId:'myCanvas',
success: (res) => {
this.base64=res.tempFilePath
}
})
uni.hideLoading();
},1200)
}).exec();
},
bcFn(){
uni.saveImageToPhotosAlbum({ //保存图片
filePath:this.base64,
success: (res) => {
uni.showToast({
title:'保存成功',
})
}
})
}
}
}
</script>
<style scoped>
.input {
width: 100%;
height: 80upx;
background: #ccc;
}
#sss {
position: absolute;
width: 750upx;
height: 100vh;
top: -99999899upx;
left: -99999899upx;
z-index: 9999;
}
.immm {
width: 750upx;
height: 90vh;
}
</style>
uniapp中使用canvas生成海报
最新推荐文章于 2024-05-09 18:38:56 发布