6.canvas 刮刮乐 练习题

"Hello World, Hello Blog"

Posted by wudimingwo on December 15, 2018

版本1.0 image.png image.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
   <style type="text/css">
      
      .wrapper{
        width: 300px;
        height: 300px;
        border: 1px solid black;
        margin: 100px auto;
        position: relative;
      }
      .wrapper canvas {
        position: absolute;
        left: 0;
        right: 0;
      }
      .wrapper div{
        position: absolute;
        left: 0;
        right: 0;
        width: 100%;
        height: 100%;
        background-color: #f00;
      }
      .wrapper div img{
        position: absolute;
        left: 0;
        right: 0;
        width: 100%;
        height: 100%;
      }
      
      
      
      
    </style>
  </head>
  
  <body>
    <div class="wrapper">
      <div class="item">
        <img src="img/2test.jpg"/>
        <canvas id="myCanvas" width="300" height="300"></canvas>
      </div>      
    </div>
    
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <script>
      
        var myCanvas = document.getElementById("myCanvas");
        var ctx = myCanvas.getContext("2d");
        
        ctx.fillRect(0,0,300,300);
        
        ctx.globalCompositeOperation = "destination-out";
        
        myCanvas.onmousedown = function (e) {
          var parent = this.parentNode.parentNode;
        	document.onmousemove = function (e) {
          	var x = e.clientX - parent.offsetLeft;
          	var y = e.clientY - parent.offsetTop;
          	ctx.beginPath();
          	ctx.arc(x,y,20,0,2 * Math.PI,1);
          	ctx.fill();
        	}
        	document.onmouseup = function () {
        	  document.onmousemove = null;
        		document.onmouseup = null;
        	}
        }