Canvas小游戏之刮刮乐

这是我参与新手入门的第三篇文章css

今天浏览网页看到一个抽奖的页面,想起了以前本身写的一个刮刮乐小游戏。就这一个简易的抽奖小游戏,写一篇文章说道说道。html

这篇文章给你带来一个小游戏的制做,在让你娱乐的同时,能够学习一下canvas的使用方法。那么接下来开始咱们的快乐之旅吧。canvas

准备一点原材料,html

一些简单的dom结构,固然你也能够写的简单一些或者更丰富一点。markdown

<body>
    <div class="box">
        <h2>刮 刮 乐</h2>
        <div class="jiang"></div>
        <div class="prize">
                <div class="content">500万</div>
                <canvas id="canvas" width="300" height="200"></canvas>
        </div>
    </div>
</body>
复制代码

处理一下原材料,css

让咱们给html穿件衣裳,俗话说:“人靠衣装马靠鞍,狗配铃铛跑的欢”,穿上css,html也变得靓丽多彩了呢。固然,根据你的喜爱,你能够给它自行设计衣服样式。样式这一块我就很少加赘述了,小伙伴们能够参考一下。app

*{
    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;
}
复制代码

下锅,canvas

万事俱备只欠东风,哦不,只欠咱们的canvas操做了。dom

  1. 建立画布
var canvas=document.querySelector('#canvas')
var ctx=canvas.getContext('2d')
复制代码
  1. 给画布一个底色
ctx.fillStyle='lightgray'
ctx.fillRect(0,0,300,200)
ctx.save()
复制代码
  1. 刮奖和中奖提示字体
ctx.font='30px serif'
ctx.fillStyle='black'
ctx.fillText('刮奖区',100,60)
ctx.save()
ctx.font='50px serif'
ctx.strokeStyle='red'
ctx.strokeText('大吉大利',50,150)
复制代码
  1. 刮奖操做

建立一个橡皮擦方块,大小本身能够设置,而后在按下鼠标移动的时候执行此函数。函数

canvas.onmousedown=function(){
    window.onmousemove=function(event){
        ctx.clearRect(event.offsetX,event.offsetY,20,20);
    }
}
canvas.onmouseup = function(){
    window.onmousemove=function(){}
}
复制代码

是否是很简单呢,让咱们看一下效果吧oop

总结

这是我几年前写的一个简易的游戏,小伙伴们能够根据本身的需求来修改一下。好比说样式、信息提示、刮奖交互等等。但愿这篇文章能够给你带来帮助。学习

相关文章
相关标签/搜索