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

總結

這是我幾年前寫的一個簡易的遊戲,小夥伴們能夠根據本身的需求來修改一下。好比說樣式、信息提示、刮獎交互等等。但願這篇文章能夠給你帶來幫助。學習

相關文章
相關標籤/搜索