Canvas Motion Blur

This example uses canvas globalAlpha to create a motion blur effect.

HTML

<div>Move your mouse to see the motion blur.</div>
<canvas id="bg" width="256" height="256"></canvas>
<canvas id="fg" width="256" height="256"></canvas>

CSS

canvas {
    position: absolute;
}
div {
    font-family: arial;
    font-size: 11px;
    margin-bottom: 10px;
}

JavaScript

var bgCanvas = document.getElementById('bg');
var bg = bgCanvas.getContext('2d');

var bgPattern;
(function() {
    var tile = new Image();
    tile.onload = function() {
        bgPattern = bg.createPattern(tile, 'repeat');
        bg.fillStyle = bgPattern;
        bg.fillRect(0, 0, bgCanvas.width, bgCanvas.height);
    };
    tile.src = 'https://www.w3schools.com/w3images/fjords.jpg';
})();

var fgCanvas = document.getElementById('fg');
var fg = fgCanvas.getContext('2d');

var mouseX = 0, mouseY = 0;
window.addEventListener('mousemove', function(event) {
    mouseX = event.pageX - fgCanvas.offsetLeft;
    mouseY = event.pageY - fgCanvas.offsetTop;
}, false);

(function loop() {
    if (bgPattern) {
        bg.globalAlpha = 0.1;
        bg.fillStyle = bgPattern;
        bg.fillRect(0, 0, bgCanvas.width, bgCanvas.height);
        bg.globalAlpha = 0.3;
        bg.drawImage(fgCanvas, 0, 0);
    }
    
    fg.clearRect(0, 0, fgCanvas.width, fgCanvas.height);
    
    var x1 = mouseX;
    var y1 = mouseY;
    var x2 = x1 + 32;
    var y2 = y1 + 32;
    fg.fillStyle = 'rgb(0, 255, 255)';
    fg.fillRect(x1, y1, 32, 32);
    fg.fillStyle = 'rgb(255, 0, 255)';
    fg.fillRect(x2, y1, 32, 32);
    fg.fillStyle = 'rgb(255, 255, 0)';
    fg.fillRect(x1, y2, 32, 32);
    fg.fillStyle = 'rgb(0, 0, 0)';
    fg.fillRect(x2, y2, 32, 32);
    setTimeout(loop, 1 / 30);
})();