canvas實戰之刮刮卡

1.效果圖

a6GU5n.png

2.html及css

<canvas id="myCanvas">
      您的瀏覽器不支持canvas,請升級!
  </canvas>
   
   
    <style>
      * {
          margin: 0;
          padding: 0;
      }
      body,html{
          width: 100%;
          height: 100%;
      }
      #myCanvas{
          background:url("images/banner.jpeg") no-repeat;
          background-size:cover;
      }
  </style>

3.js

<script>
      (function(){
          var canvasNode = document.querySelector("#myCanvas");
          canvasNode.width = window.innerWidth;
          canvasNode.height = window.innerHeight;
          var ctx = canvasNode.getContext('2d');

          // 繪製覆蓋層 目標圖像
          ctx.fillStyle = '#ccc';
          ctx.fillRect(0,0,canvasNode.width,canvasNode.height);


            // 圖片合成
          ctx.globalCompositeOperation = 'destination-out';


          ctx.lineWidth = 30;
          ctx.lineCap = 'round';


          // 簽名板 源圖像
          canvasNode.onmousedown = function(event) {
                  ctx.beginPath();
                  ctx.moveTo(event.offsetX,event.offsetY);
               
              document.onmousemove = function(event) {
                  ctx.lineTo(event.clientX - canvasNode.offsetLeft,event.clientY - canvasNode.offsetTop);
                  ctx.stroke();
              };
              document.onmouseup = function() {
                  this.onmousemove = null;
              }
          }


      })();
  </script>

4..總結

  • 這個案例主要是搞清楚這個屬性 globalCompositeOperation 屬性設置或返回如何將一個源(新的)圖像繪製到目標(已有)的圖像上。注意值是用的 destination-out,在源圖像以外顯示目標圖像。只有源圖像以外的目標圖像部分會被顯示,源圖像是透明的。css

  • 在設置圖片合成方式那裏,注意前面是目標圖像,後面是源圖像。html

相關文章
相關標籤/搜索