HTML5 canvas擦抹模糊玻璃特效


源码介绍

简要教程

这是一款HTML5 canvas擦抹模糊玻璃特效。该特效类似橡皮擦特效,当鼠标在屏幕上涂抹时,原本模糊的地方会变成清晰的图片。

使用方法

在页面中引入下面的文件。

<link rel="stylesheet" type="text/css" href="css/normalize.css" />
<link rel="stylesheet" href="css/style.css">
<script src="js/jquery.min.js" type="text/javascript"></script>             
                
HTML结构
<div class="canvas-bg-image">
  <div></div>
</div>
                
JavaScript
// defining variables
// c and h are canvases, f and b are contexts
let c, h, f, b, img, mouseX = null,
    mouseY = null,
    array = [],
    startTime = 0,
    over500msElapsed = true

$("body").mousemove((e) => {
  mouseX = e.clientX
  mouseY = e.clientY
  startTime = Date.now()
  over500msElapsed || onImageLoad()
})

// handle mouse leaving window (set null) or resize (rebuild canvases)
$(window)
  .on("blur mouseout", function() {
  mouseX = mouseY = null
}).on("resize", function() {
  c && c.parentNode && c.parentNode.removeChild(c)
  setUpCanvases()
})

setUpCanvases()

function setUpCanvases() {
  const bodyWidth = $("body").width()
  const bodyHeight = $("body").height()
  c = document.createElement("canvas")
  c.width = bodyWidth
  c.height = bodyHeight
  c.style.position = "absolute"
  c.style.top = 0
  c.style.left = 0
  $("body").append(c)
  h = document.createElement("canvas")
  h.width = bodyWidth
  h.height = bodyHeight
  // set up contexts
  if (c.getContext && c.getContext("2d") && (f = c.getContext("2d"),
                                             b = h.getContext("2d"), b.lineCap = "round", b.shadowColor = "#000", !img)) {
    // loads image (never added to DOM) so that it can be added to canvas (browser only needs to download it once)
    img = new Image
    // add listener before setting source so it will definitely capture the event
    $(img).one("load", onImageLoad)
    $(img).attr("src", "https://static.canva.com/static/images/bg_tiles_color.2.jpg")
  }
}

function onImageLoad() {
  let currentTime = Date.now()
  over500msElapsed = currentTime > startTime + 500 ? false : true
  
  // push to start of array
  mouseX && over500msElapsed && array.unshift({
    time: currentTime,
    x: mouseX,
    y: mouseY + $("body").scrollTop()
  })
  
  // trims array - removes all items older than 1s
  for (let i = 0; i  1000) {
      array.length = i
    }
  }
  
  if (array.length > 0) {
    requestAnimationFrame(onImageLoad)
  }
  
  // clear canvas2 by its own width and height
  b.clearRect(0, 0, h.width, h.height)
  
  // loop through each item in array
  for (i = 1; i 
                

该HTML5 canvas擦抹模糊玻璃特效插件的codepen网址为:https://codepen.io/samwooly/pen/qpeaNL



点赞(0) 打赏

立即下载

点击下载

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部