五角星评分控件
<body>
<style>
#box {
border: 1px solid black;
margin: 100px 0 0 100px;
width: 510px;
height: 100px;
position: absolute;
}
</style>
<h1>点亮小星星:</h1>
<div id="box"></div>
<script>
//画五角星
//1.利用圆形画五角星,在圆上找均匀分布的五个点
//2.利用三角函数算出每个点的坐标,作为连线的坐标
//3.将五个点两两间隔连接起来,形成五角星。
Object.prototype.start = function (x, y, r, color = "gray", ancolor = "yellow") {
this.beginPath()
var arr = []
var deg = Math.PI / 180
for (let i = 0; i < 5; i++) {
//1.利用圆形画五角星,在圆上找均匀分布的五个点
//2.利用三角函数算出每个点的坐标,作为连线的坐标
var x1 = x + Math.cos((72 * i - 90) * deg) * r
var y1 = y + Math.sin((72 * i - 90) * deg) * r
arr.push(x1, y1)
}
//3.将五个点两两间隔连接起来,形成五角星。
this.moveTo(arr[0], arr[1])
this.lineTo(arr[4], arr[5])
this.lineTo(arr[8], arr[9])
this.lineTo(arr[2], arr[3])
this.lineTo(arr[6], arr[7])
this.lineTo(arr[0], arr[1])
this.fillStyle = color
this.fill()
// this.stroke()
}
//封装一个canvas函数,在盒子里面添加一个人canvas根据盒子的宽高来决定五角星的大小
Object.prototype.canvas = function (n, color) {
var canvas = document.createElement("canvas")
var pen = canvas.getContext("2d")
var r = this.offsetHeight / 2
canvas.heigth = r * 2
canvas.width = (this.offsetHeight + 4) * 5
this.appendChild(canvas)
//判断点亮五角星的个数,将要改变的五角星填充为黄色
for (let i = 0; i < 5; i++) {
if (i < n) {
pen.start(r + r * 2 * i, r, r, "yellow")
} else {
pen.start(r + r * 2 * i, r, r, color)
}
}
}
</script>
<script>
var box = document.querySelector("#box")
box.canvas()
//给box绑定移动事件,通过事件的属性和弹性盒子的属性来计算出鼠标移动到那个五角星,将前面所有的五角星的填充颜色变为黄色
box.onmousemove = function (el) {
var n = Math.ceil((el.clientX - this.offsetLeft) / (this.offsetHeight + 4))
this.innerHTML = " "
this.canvas(n)
}
</script>