)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Canvas Ring on Image

  1. const uploadInput = document.body.appendChild(
  2.   Object.assign(document.createElement('input'), {
  3.     type: 'file',
  4.     accept: 'image/png, image/jpeg'
  5.   })
  6. )
  7. uploadInput.style.display = 'block'
  8.  
  9. const canvas = document.body.appendChild(document.createElement('canvas'))
  10. const c = canvas.getContext('2d')
  11.  
  12. canvas.style.width = '70%'
  13.  
  14. let sampleSize
  15. const steps = 100
  16. const step = (Math.PI * 2) / steps
  17.  
  18. let interval
  19.  
  20. const ring = () => {
  21.   clearInterval(interval)
  22.   let x = imageEl.width / 2,
  23.     y = imageEl.height / 2,
  24.     rad = imageEl.width * 0.3,
  25.     theta = 0,
  26.     px,
  27.     py,
  28.     pxs = [],
  29.     spy = []
  30.   ;(pys = []), (im = []), (rects = [])
  31.  
  32.   for (let i = 0; i < steps; i++) {
  33.     px = x + rad * Math.cos(theta)
  34.     py = y + (rad / 2) * Math.sin(theta)
  35.     theta += step
  36.     pxs[i] = px
  37.     pys[i] = spy[i] = py
  38.     im[i] = c.getImageData(px, py, sampleSize, sampleSize)
  39.     rects[i] = [px, py, sampleSize, sampleSize]
  40.   }
  41.  
  42.   interval = setInterval(() => {
  43.     for (let i = 0; i < steps; i++) {
  44.       pys[i] -= 1
  45.       c.putImageData(im[i], pxs[i], pys[i])
  46.       v = (y - spy[i]) / rad
  47.       c.fillStyle = 'rgba(0,0,0,' + v + ')'
  48.       c.fillRect(pxs[i] - 1, pys[i], sampleSize + 2, sampleSize - 1)
  49.     }
  50.   }, 16)
  51. }
  52.  
  53. const imageEl = new Image()
  54. imageEl.src = 'https://snippet.zone/wp-content/uploads/2022/01/taho-scaled.jpg'
  55. imageEl.onload = () => {
  56.   canvas.width = imageEl.width
  57.   canvas.height = imageEl.height
  58.   c.drawImage(imageEl, 0, 0)
  59.   sampleSize = imageEl.width / 25
  60.  
  61.   ring()
  62. }
  63.  
  64. const reader = new FileReader()
  65.  
  66. reader.addEventListener('load', () => {
  67.   imageEl.src = reader.result
  68. })
  69.  
  70. uploadInput.addEventListener('change', e => {
  71.   const file = e.target.files[0]
  72.   if (file != null) {
  73.     reader.readAsDataURL(file)
  74.   }
  75. })

Upload an image and it will have a distortion ring drawn on it

snippet.zone ~ 2021-24 /// {s/z}