I'm participating in the "On the Code Nuggets Challenge" For details, please see: The Code On The Nuggets Challenge is here!
foreword
I saw a scratch effect on a lottery website today. I thought it was very interesting, so I planned to imitate it. After some simple thinking, I probably got the basic idea. The overall effect uses Canvas to create a scratch-off music that sets the probability of the lottery. The production process is not tedious and very simple.
experience
make
html
A centered header and scratch card area.
<h1 style="text-align: center;">刮刮乐</h1>
<div id="ggk">
<div class="jp">不抽大嘴巴子</div>
<canvas id="canvas" width="400" height="100"></canvas>
</div>
复制代码
css
add style
#ggk {
width: 400px;
height: 100px;
position: relative;
left: 50%;
transform: translate(-50%, 0);
}
.jp,
canvas {
position: absolute;
width: 400px;
height: 100px;
left: 0;
top: 0;
text-align: center;
font-size: 25px;
line-height: 100px;
color: deeppink;
}
复制代码
default
Mouse dragging does not select text.
document.addEventListener("selectstart", function (e) {
e.preventDefault();
})
复制代码
canvas
Set the Canvas canvas.
let canvas = document.querySelector("#canvas");
let ctx = canvas.getContext('2d');
ctx.fillStyle = 'darkgray';
ctx.fillRect(0, 0, 400, 100);
复制代码
draw
Determine if the mouse is pressed.
let isDraw = false;
canvas.onmousedown = function () {
isDraw = true;
}
复制代码
If the mouse is pressed isDraw is true, it can be smeared, and the gray of the Canvas is smeared off.
canvas.onmousemove = function (e) {
if (isDraw) {
let x = e.pageX - ggkDom.offsetLeft + ggkDom.offsetWidth / 2;
let y = e.pageY - ggkDom.offsetTop;
ctx.beginPath();
ctx.arc(x, y, 30, 0, 2 * Math.PI);
ctx.globalCompositeOperation = 'destination-out';
ctx.fill();
ctx.closePath();
}
}
复制代码
When the mouse is up, isDraw is flase
document.onmouseup = function () {
isDraw = false;
}
复制代码
prize
Set the prize, p is the winning rate.
let arr = [
{ content: '一等奖:一个大嘴巴子', p: 0.1 },
{ content: '二等奖:两个大嘴巴子', p: 0.2 },
{ content: '三等奖:三个大嘴巴子', p: 0.3 }
];
复制代码
create a random number
let sj = Math.random();
复制代码
The random number is used to judge, and after the judgment is successful, the successful value is returned.
if (sj < arr[0].p) {
jp.innerHTML = arr[0].content;
} else if (sj < arr[1].p) {
jp.innerHTML = arr[1].content;
} else if (sj < arr[2].p) {
jp.innerHTML = arr[2].content;
}
复制代码
at last
In fact, you can also use this function to make signatures, paintings, etc., because they are all smearing or painting things, which are probably similar. If you are interested, you can learn more about them.
There are 16 days until the National Day and 16 days until the holiday! ! !