大致效果 点击不同颜色三角形对应不同事件
triangle.png
1. 通过offsetX offsetY实现
HTML代码
<div class="box" @click="clickBox"></div>
css代码
.box {
width: 0px;
height: 0px;
border-width: 100px;
border-style: solid;
border-color: blue blue pink pink;
}
JS代码
clickBox(event) {
let X = event.offsetX;
let Y = event.offsetY;
if (X > 0 && Y < 0) {
//第一种情况
console.log("蓝色 右上");
} else if (X < 0 && Y > 0) {
//第二种情况
console.log("粉色 左下");
} else if (X < 0 && Y < 0) {
//第三种情况 里面分俩种情况
if (X > Y) {
console.log("蓝色 左上");
} else {
console.log("粉色 左下");
}
} else if (X > 0 && Y > 0) {
//第四种情况 里面分俩种情况
if (Y > X) {
console.log("粉色 右下");
} else {
console.log("蓝色 右上");
}
}
},
2.通过canvas里getImageData方法来获取点击的颜色来判断想要触发对应事件
HTML代码
<canvas id="boxDom" width="200" height="200" @click="clickBox"></canvas>
js 代码
methods: {
init() {
let bg = document.getElementById("boxDom");
console.log(bg)
let ctx = bg.getContext("2d");
//绘制三角形
ctx.beginPath();
ctx.moveTo(0, 0); //从A(100,0)开始
ctx.lineTo(0, 200); //从A(100,0)开始,画到B (0,173)结束
ctx.lineTo(200, 200); //B(0,173)-C(200,173)
let grd = ctx.createLinearGradient(0, 0, 200, 0); //使用渐变颜色填充,从(0,0)到(200,0) (左到右)
grd.addColorStop(0, "pink"); //起始颜色
ctx.fillStyle = grd; //以上面定义的渐变填充
ctx.fill(); //闭合形状并且以填充方式绘制出来
ctx.beginPath();
ctx.moveTo(200, 0); //从A(100,0)开始
ctx.lineTo(200, 200); //从A(100,0)开始,画到B (0,173)结束
ctx.lineTo(0, 0); //B(0,173)-C(200,173)
let grd2 = ctx.createLinearGradient(0, 0, 200, 0); //使用渐变颜色填充,从(0,0)到(200,0) (左到右)
grd2.addColorStop(0, "blue"); //起始颜色
ctx.fillStyle = grd2; //以上面定义的渐变填充
ctx.fill(); //闭合形状并且以填充方式绘制出来
},
clickBox(e) {
let bg = document.getElementById("boxDom");
let ctx = bg.getContext("2d");
let imageData = ctx.getImageData(e.offsetX, e.offsetY, 1, 1);
let pixel = imageData.data;
let r = pixel[0];
let g = pixel[1];
let b = pixel[2];
let a = pixel[3] / 255;
a = Math.round(a * 100) / 100;
let rHex = r.toString(16);
r < 16 && (rHex = "0" + rHex);
let gHex = g.toString(16);
g < 16 && (gHex = "0" + gHex);
let bHex = b.toString(16);
b < 16 && (bHex = "0" + bHex);
let rgbaColor = "rgba(" + r + "," + g + "," + b + "," + a + ")";
let rgbColor = "rgb(" + r + "," + g + "," + b + ")";
let hexColor = "#" + rHex + gHex + bHex;
console.log(rgbaColor, rgbColor, hexColor);
},
}
mounted(){
this.init();
}
网友评论