绘制八边形,不切图做导航按钮样式
封装绘制八边形函数
export function drawOctagon( id, width, height, text, startFillColor, endFillColor, startLineColor, endLineColor, textColor ) { function polygon(poly, context) { context.beginPath() context.moveTo(poly[0], poly[1]) //遍历顶点绘制图形 for (var i = 2; i < 16; i += 2) { context.lineTo(poly[i], poly[i + 1]) // console.log(poly[i], poly[i + 1]) } context.closePath() context.fill() context.stroke() } // debugger var canvas = id === typeof 'string' ? document.querySelector(id) : id var context = canvas.getContext('2d') var grd = context.createLinearGradient(0, 0, width, 0) var gradient = context.createLinearGradient(0, 0, width, 0) context.clearRect(0, 0, width, height) grd.addColorStop(0, startFillColor) grd.addColorStop(1, endFillColor) gradient.addColorStop(0, startLineColor) gradient.addColorStop(1, endLineColor) context.fillStyle = grd context.strokeStyle = gradient context.lineWidth = 1 // 2个像素宽 //顶点数组 var poly = [ 2, height / 4, 2, (3 * height) / 4, height / 4, height - 2, width - height / 4, height - 2, width - 2, (3 * height) / 4, width - 2, height / 4, width - height / 4, 2, height / 4, 2, ] polygon(poly, context)
//绘制文字,以及文字样式 context.font = '14px Microsoft YaHei' context.fillStyle = textColor context.textAlign = 'center' context.textBaseline = 'middle' context.fillText(text, width / 2, height / 2) }
调用函数实现效果
需要点击切换样式的时候需要在点击时重绘canvas