使用canvas绘制四个角的指定样式
1. 实现思路
项目中通过Vue
进行封装一个公用的组件形式, 将内容div
和canvas
放在一个父盒子中, 通过定位实现视觉效果
<template>
<div class="ai-capability-video-bgc">
<canvas
class="ai-capanbility-canvas"
:id="canvasId"
:width="canvasWidth"
:height="canvasHeight"
v-if="canvasFlag"
></canvas>
<div class="main-box">
<slot></slot>
</div>
</div>
</template>
id
是每次自动生成的,就是为了防止出现重复的id
…
created(){
this.canvasId = `ai-capanbility-canvas_${+new Date()}_${Math.ceil(Math.random() * 1000000)}`
}
v-if="canvasFlag"
是为了获取到父盒子的宽高之后再渲染JS
完整代码
data() {
return {
canvasId: '',
canvasWidth: 0,
canvasHeight: 0,
canvasFlag: false
}
},
created() {
this.canvasId = `ai-capanbility-canvas_${+new Date()}_${Math.ceil(
Math.random() * 1000000
)}`
},
mounted() {
this.initDom()
},
methods: {
initDom() {
// 获取宽高
const { clientWidth, clientHeight } = document.querySelector(
'.ai-capability-video-bgc'
)
this.canvasWidth = clientWidth
this.canvasHeight = clientHeight
this.canvasFlag = true
this.$nextTick(() => {
// 设置每次划线的长度
const canvasWidth = 6
// 两倍划线的长度
const doubleCanvasWidth = canvasWidth * 2
// 根据元素的 宽 - 划线的长度
const calcWidthByOne = clientWidth - canvasWidth
// 根据元素的 宽 - 划线的长度 * 2
const calcWidthBySceond = clientWidth - doubleCanvasWidth
// 根据元素的 高 - 划线的长度
const calcHeightByOne = clientHeight - canvasWidth
// 根据元素的 高 - 划线的长度 * 2
const calcHeightBySceond = clientHeight - doubleCanvasWidth
const c = document.getElementById(this.canvasId)
const ctx = c.getContext('2d')
ctx.moveTo(0, doubleCanvasWidth)
ctx.lineTo(0, canvasWidth)
ctx.lineTo(canvasWidth, 0)
ctx.lineTo(doubleCanvasWidth, 0)
ctx.moveTo(calcWidthBySceond, 0)
ctx.lineTo(calcWidthByOne, 0)
ctx.lineTo(clientWidth, canvasWidth)
ctx.lineTo(clientWidth, doubleCanvasWidth)
ctx.moveTo(clientWidth, calcHeightBySceond)
ctx.lineTo(clientWidth, calcHeightByOne)
ctx.lineTo(calcWidthByOne, clientHeight)
ctx.lineTo(calcWidthBySceond, clientHeight)
ctx.moveTo(doubleCanvasWidth, clientHeight)
ctx.lineTo(canvasWidth, clientHeight)
ctx.lineTo(0, calcHeightByOne)
ctx.lineTo(0, calcHeightBySceond)
ctx.strokeStyle = '#2DFFFE'
ctx.lineWidth = 3
ctx.stroke()
})
}
}
css部分
.ai-capability-video-bgc {
position: relative;
height: 100%;
width: 100%;
.ai-capanbility-canvas {
position: absolute;
z-index: 10;
height: 100%;
width: 100%;
}
.main-box {
height: 100%;
width: 100%;
}
}