2018-11-04

Konva.js + Spot light effect (Masking)

這篇文章提供利用 Konva.js 實現 Spotlight 效果之範例。

++
底圖 + 80%填充摭黑 + Cutout Spotlight

Konva.js 部分之程式碼 :

...

<div id="stage-parent" style="width: 50%;">
  <div id="scene_container">
  </div>
</div>

...

<script>

  var stage = new Konva.Stage({
    container: 'scene_container',
    width: 800,
    height: 600
  })

  var stage_scale =1
  var fitStageIntoParentContainer =function() {
    var container = document.querySelector('#stage-parent')

    // now we need to fit stage into parent
    var containerWidth = container.offsetWidth
    // to do this we need to scale the stage
    stage_scale = containerWidth / 800

    stage.width(800 * stage_scale)
    stage.height(600 * stage_scale)
    stage.scale({ x: stage_scale, y: stage_scale })
    stage.draw()
  }
  window.addEventListener('resize', fitStageIntoParentContainer)
  fitStageIntoParentContainer()

  //
  // background layer
  //
  var layer = new Konva.Layer()
  stage.add(layer)

  var bgImg = new Konva.Image({
    width: 800,
    height: 600
  })
  layer.add(bgImg)
  var bgImgObj = new Image()
  bgImgObj.onload = function() {
    bgImg.image(bgImgObj)
    layer.draw()
  }
  bgImgObj.src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJG-1Bt_pth4w6CLtGXS5W6SY8vGtrQ6Jk3VOo4dY6NinzpcW4XAQpZi2VQFm-IQs3FwGC7IptmNtFraJHEH8Zj4SQQxJ_TXo054m7WLxfgOO8dS_iuvwXyqxdp15M5anhSxwv08m8j-Cg/s1600/DSC06624m.jpg'

  //
  // mask layer
  //
  var layer_mask =new Konva.Layer()
  stage.add(layer_mask)
  var opacity_rect = new Konva.Rect({
    x: 0,
    y: 0,
    width: 800,
    height: 600,
    fill: 'black',
    draggable: false,
    opacity: 0.8
  })
  layer_mask.add(opacity_rect)

  var transparent_circle = new Konva.Circle({
    x: 400,
    y: 300,
    radius: 200,
    fill: 'black',
    draggable: true,
    globalCompositeOperation: 'destination-out'
  })
  layer_mask.add(transparent_circle)
  layer_mask.draw()

</script>
Konva.js 執行結果 Demo (Spotlight 可拖曳) :