記錄通過🤔小功能點css
小程序頁面增長水印html
效果git
由於全部頁面都要加水印,因此確定是要用自定義組件實現。github
第一種json
最開始考慮的是canvas生成圖片,轉換成base64作一張背景圖,而後才瞭解到水印不能直接在元素上做爲背景做爲頁面的最底層,很容易被其餘東西覆蓋,因此水印必定是要要fixed在頁面的最頂層。 canvas生成圖片,可是要借用其餘插件轉成base64canvas
第二種小程序
能夠採用DOM元素靠樣式實現,也不須要依賴插件,感受這個更加的不錯。因而就代碼擼起來,而後每一個頁面都能有水印了,看起來是成功了。可是!!當切換登陸人之後發現有的頁面水印上的登陸人怎麼仍是上一個登陸人的信息呢?原來component的生命週期事件是依賴於所在頁面的,若是頁面從未銷燬過,Component有些事件就不會再次觸發了。因而,我產生了第一種思路,如何能讓組件監聽到所在頁面的聲明週期,看小程序文檔確實有這樣的方法,可是依賴的基礎庫版本比較高,那用戶是低版本基礎庫豈不是不會生效了。emmmm再想一想,那登陸的時候保證讓打開過的全部頁面銷燬就能夠了啊,當前跳轉登陸頁使用的方法是wx.navigateTo(會保留當前頁面,而後跳轉,因此有些頁面不銷燬,組件獲取用戶id的方法就不會觸發第二次了),那退出登陸的時候調用wx.reLaunch(關閉全部頁面,而後跳轉頁面)方法就okxss
import UPNG from './upng';
const CANVAS = 'water_mark_id';
Component({
data: {
text: '請勿外傳',
imgBase64: '',
color:'rgba(0,0,0,0.5)'
},
attached() {
const { text, color } = this.data;
const ctx = wx.createCanvasContext(CANVAS, this);
ctx.rotate((335 * Math.PI) / 180);
ctx.setFontSize(20);
ctx.setFillStyle(color);
ctx.fillText(text, 0, 100);
ctx.draw(false, () => {
setTimeout(() => {
wx.canvasGetImageData({
canvasId: CANVAS,
x: 0,
y: 0,
width: 120,
height: 100,
success: (res) => {
const pngData = UPNG.encode([res.data.buffer], res.width, res.height);
const base64 = wx.arrayBufferToBase64(pngData);
this.setData({ imgBase64: 'data:img/jpg;base64,' + base64 });
},
fail: (err) => {
console.log(err);
}
}, this);
}, 2000);
});
}
});
複製代碼
json文件ui
{
"component": true
}
複製代碼
wxml文件
<view class="water-mark-mask" style="background:url('{{imgBase64}}')">
<canvas canvas-id="water_mark_id"></canvas>
</view>
複製代碼
wxss文件
.water-mark-mask {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1000;
pointer-events: none;
opacity: 0.1;
}
複製代碼
js代碼
Component({
data: {
text: '請勿外傳',
// color: 'rgba(0,0,0,0.03)',
color: 'rgba(0,0,0,0.5)',
rows: [],
cols: []
},
// 組件在頁面上掛載時觸發,注意若是頁面沒卸載過,該事件就不會觸發第二次
attached() {
const { windowWidth, windowHeight } = wx.getSystemInfoSync();
const rows = Math.ceil(windowWidth / (30 * this.data.text.length));
const cols = Math.ceil(windowHeight / 100);
this.setData({
rows: new Array(rows),
cols: new Array(cols)
});
},
})
複製代碼
json文件
{
"component": true
}
複製代碼
wxml文件
<view class='water-mark-mask'>
<view class='row' wx:for="{{rows}}" wx:key="index">
<view class='col' wx:for="{{cols}}" wx:key="index" style="color:{{color}}">{{text}}</view>
</view>
</view>
複製代碼
wxss文件
.water-mark-mask {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 9999;
display: flex;
flex-direction: row;
justify-content: space-between;
pointer-events: none; //無視鼠標事件,至關於鼠標事件透傳下去同樣
flex:1
}
.row{
display: flex;
flex-direction: column;
align-items: center;
}
.col{
transform: rotate(-45deg);
height: 200rpx;
}
複製代碼
這樣就行了,引用到頁面就👌了