canvas刮刮乐

2019-12-27  本文已影响0人  为了_理想

在学习canvas 菜鸟一个 写的一个小demo

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>刮刮乐</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        #clock {
            width: 500px;
            height: 200px;
            text-align: center;
            line-height: 200px;
            font-size: 36px;
            letter-spacing: 10px;
        }
        #myCanvas {
            position: absolute;
            top: 0;
            left: 0%;
        }
    </style>
</head>

<body>
    <div id="clock">
        <canvas id="myCanvas" width="500" height="200"></canvas>
        <div id="content">谢谢惠顾</div>
    </div>
    <script src="./index.js"></script>
    <script>
       new Canvas({ 
          el:'#clock',
          data:{ 
              x:0,
              y:0,
              drawingWidth:5,
              drawingHeigth:5,
              background:'gray'
          }
      })
   
    </script>
</body>
</html>

js


function Canvas(option) {
    this.init(option)
  }
Canvas.prototype = {
    init: function (options) {
        this.initData(options);
        console.log(2)
    },
  注意这里的this是指向当前的原型的  和 外面的数据是没有任何关系的  这里修改了他的this  那么这里面的this数据就指向了当前修改的this  和外面是没关系的 [注意 注意 注意]
    initData: function (options) {
        this.canvas = document.getElementById('myCanvas')
        this.ctx = this.canvas.getContext("2d");
        this.width = this.canvas.width
        this.height = this.canvas.height

        this.x = options.data.x
        this.y = options.data.y
        this.drawingWidth = options.data.drawingWidth
        this.drawingHeigth = options.data.drawingHeigth
        
        this.ctx.rect(this.x, this.y, this.width, this.height)
        this.ctx.fillStyle = options.data.background;
        this.ctx.fill()
        this.canvasEvent()
        this.changeFont()
    },
    canvasEvent:function(){ 
        this.canvas.onmousedown = ()=>{ 
            this.canvas.onmousemove = (e)=>{ 
                if(e.clientX == this.width - 1 || e.clientY == this.height - 1){ 
                    this.canvas.onmousemove = null
                    return 
                }
                  this.ctx.clearRect(e.clientX,e.clientY,this.drawingWidth,this.drawingHeigth)
            }
        }
        this.canvas.onmouseup = ()=>{ 
            this.canvas.onmousemove = null
            return 
        }
    },

    changeFont:function(){ 
        var arr = ['今天学习javascript', '今天学习node', '今天学习vue', '今天学习react', '今天学习typeScript', '今天学习小程序', '今天学习html', '今天学习css']
        var n = Math.floor(Math.random() * arr.length)
        if (n < 2) {
            n = arr.length - 1
        }
       document.getElementById('content').innerHTML = arr[n]
    }
}
上一篇下一篇

猜你喜欢

热点阅读