Advertisement

Interactive Canvas Liquid Image Distortion

| by Vladimir | 2 min read | code by Frank
Intermediate

Tech & Dependencies

HTML CSS JavaScript

Features

  • Canvas API
  • Grid System
  • Mouse Interaction
  • Image Slicing

Browser Support

Chrome 4+ Edge 12+ Firefox 3.6+ Safari 4+

Core

This Interactive Canvas Liquid Image Distortion transforms a static image into a playful, fluid surface. By subdividing the image into a grid of tiny cells, the script manipulates the texture coordinates of each cell in response to mouse movement. The result is a “jelly-like” or refractive glass effect where the image appears to warp and ripple under the user’s cursor.

Core Technique: Source Coordinate Sifting

The magic of this effect lies not in moving the cells themselves, but in moving what they display. It leverages the 9-argument syntax of the HTML5 Canvas drawImage() method.

1. The Grid System

The script initializes by creating a grid of Cell objects. Each cell covers a specific rectangular area of the canvas (cellWidth by cellHeight).

2. Canvas Slicing (The Magic)

Normally, when animating on canvas, you update the destination coordinates (dx, dy). Here, the destination coordinates remain fixed (the grid doesn’t break). Instead, the code updates the source coordinates (sx, sy) based on the mouse position.

// ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

draw(){
    ctx.drawImage(
        myImage, 
        this.x + this.drawOffsetX, // Shift the source X
        this.y + this.drawOffsetY, // Shift the source Y
        cellWidth, cellHeight,     // Source dimensions
        this.x, this.y,            // Fixed destination X/Y
        cellWidth, cellHeight      // Destination dimensions
    );
}

3. Proximity Physics

The update() method calculates the distance between the mouse and the center of the cell using the Pythagorean theorem.

  • Hover: If the mouse is close (distance < mouse.radius), the drawOffsetX/Y values are adjusted away from the mouse, creating the distortion.
  • Rest: If the mouse moves away, a simple easing equation (this.drawOffsetX -= this.drawOffsetX/12) smoothly returns the offset to 0, settling the image back to its original state.

Browser Support

This effect relies on the standard Canvas API 2D context, which is supported in all modern browsers. Performance depends on the number of cells (grid density).

Key Technologies:

  • Canvas API: Specifically getContext('2d') and drawImage().
  • ES6 Classes: For organizing the Cell logic.
Advertisement