This is my third article on getting started
Browsing the web today, I saw a lottery page and remembered a scratch-off game I had written before. Write an article about this simple lottery game.
This article brings you a small game to make, let you have fun at the same time, you can learn how to use canvas. So let’s start our happy journey.
Get a little bit of raw material, HTML
Some simple DOM structures, of course, you can write simpler or richer.
<body>
<div class="box">
<h2>Scratch music</h2>
<div class="jiang">prize</div>
<div class="prize">
<div class="content">5 million</div>
<canvas id="canvas" width="300" height="200"></canvas>
</div>
</div>
</body>
Copy the code
Let’s do the raw material, CSS
Let’s put on clothes for HTML. As the saying goes, “Clothes make a man, horses make a saddle, and dogs run happily with bells.” Put on CSS, HTML has become beautiful and colorful. Of course, depending on your preferences, you can give it its own clothing design. Style this piece I do not add tautology, small partners can refer to.
* {margin: 0;
padding: 0;
}
body{
position: relative;
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.box{
margin: 60px 100px;
width:300px;
height:500px;
border:1px solid red;
background:rgba(255.0.0.8);
}
h2{
text-align: center;
font-size: 30px;
color:cyan;
}
.jiang{
width:200px;
height: 200px;
border-radius: 50%;
background-color:rgba(255.0.0.3);
line-height: 200px;
text-align: center;
font-size: 60px;
color:gold;
margin:20px auto;
}
.prize{
height:200px;
position: relative;
}
.content{
width:300px;
height: 200px;
background-color:rgba(0.0.255.0.1);
line-height: 200px;
text-align: center;
font-size: 60px;
color:purple;
margin:20px auto;
}
#canvas{
position:absolute;
top: 0;
left: 0;
cursor: url('xpc.cur'),pointer;
}
Copy the code
The pot, canvas
All that’s left is our canvas operation.
- Create a canvas
var canvas=document.querySelector('#canvas')
var ctx=canvas.getContext('2d')
Copy the code
- Give the canvas a background color
ctx.fillStyle='lightgray'
ctx.fillRect(0.0.300.200)
ctx.save()
Copy the code
- Scraping and winning tips font
ctx.font='30px serif'
ctx.fillStyle='black'
ctx.fillText('Scrape zone'.100.60)
ctx.save()
ctx.font='50px serif'
ctx.strokeStyle='red'
ctx.strokeText('Good luck'.50.150)
Copy the code
- La tombola operation
Create an eraser square of any size and execute this function when moving with the mouse down.
canvas.onmousedown=function(){
window.onmousemove=function(event){
ctx.clearRect(event.offsetX,event.offsetY,20.20);
}
}
canvas.onmouseup = function(){
window.onmousemove=function(){}}Copy the code
Isn’t that easy? Let’s see how it works
conclusion
This is a simple game I wrote a few years ago, and friends can modify it according to their own needs. Examples include styles, message prompts, scraping interactions, and so on. I hope this article will help you.