Skip to content

Instantly share code, notes, and snippets.

@n1ywb
Created September 22, 2018 04:56
Show Gist options
  • Save n1ywb/46d63867bde5ee7025725ef2dabeedfd to your computer and use it in GitHub Desktop.
Save n1ywb/46d63867bde5ee7025725ef2dabeedfd to your computer and use it in GitHub Desktop.
canvas d3
<script src="https://cdnjs.cloudflare.com/ajax/libs/stackblur-canvas/1.4.1/stackblur.min.js"></script>
<canvas
id=blurryText
width=200
height=200
></canvas>
<canvas
id=slot
width=200
height=200
></canvas>
(()=>{
let canvas = document.getElementById('blurryText');
let ctx = canvas.getContext('2d');
let slotCanvas = document.getElementById('slot');
let slotCtx = canvas.getContext('2d');
let height = 200;
let width = 200;
let slotHeight = 30;
let slotWidth = 100;
let slotStart = 0 - slotWidth;
let slotEnd = width;
let slotX = slotStart;
let slotY = 90;
let textX = 5;
let textY = 115;
let bgColor = 'lightblue';
let textColor = 'black'
let font = '24pt sans';
let text = 'Hello, world';
let blurRadius = 10;
// background
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = bgColor;
ctx.fillRect(0,0,width,height);
// text to be blurred
ctx.fillStyle = textColor;
ctx.font = font;
ctx.fillText(text, textX, textY);
// blur text
StackBlur.canvasRGB(canvas, 0, 0, width, height, blurRadius);
// save context
let blurryText = ctx.getImageData(0, 0, width, height);
let lastTime = 0;
let step = (time) => {
let droppedFrames = (time - lastTime) / 1000 / 6;
// slot
// ctx.restore();
slotCtx.putImageData(blurryText, 0, 0);
slotCtx.fillStyle = 'lightblue';
slotCtx.fillRect(slotX,slotY,slotWidth,slotHeight);
slotCtx.clearRect(slotX,slotY,slotWidth,slotHeight);
// clear text
slotCtx.globalCompositeOperation = 'destination-over';
slotCtx.fillStyle = textColor;
slotCtx.fillText(text, textX, textY);
// slot background
slotCtx.fillStyle = bgColor;
slotCtx.fillRect(slotX,slotY,slotWidth,slotHeight);
// 5. border
// that's trivial at this point
// just draw whatever you like on top of it all
// Calculate animation step
slotX = slotX > slotEnd ? slotStart : slotX + (time - lastTime) / 10;
lastTime = time;
window.requestAnimationFrame(step);
};
lastTime = performance.now();
step(lastTime);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
#canvas {
border: 1px solid black;
width: 200px;
height: 200px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment