Created
December 5, 2017 09:26
-
-
Save mgussekloo/79d927e1f011e26052114a5df8723ab9 to your computer and use it in GitHub Desktop.
Draw smooth dashed sine wave with vanilla js and canvas drawing, for trail-like UI element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// $('.js-trail-canvas').drawTrail() | |
var checkTrails = function() { | |
$('.js-trail').remove(); | |
ImagesLoaded(document.querySelector('.with-trail'), function() { | |
$('.js-trail-container').each(function() { | |
var $container = $(this); | |
var w = $container.width(), h = $container.height(); | |
if (w == 0 || h == 0) return; | |
var $canvas = $('<canvas></canvas>') | |
.addClass('js-trail') | |
.prop({ | |
width: w, | |
height: h | |
}); | |
$container.append($canvas) | |
var ctx = $canvas[0].getContext("2d"); | |
ctx.imageSmoothingEnabled = true; | |
ctx.lineWidth = 5; | |
ctx.setLineDash([10]); | |
ctx.strokeStyle = '#C7CBDC'; | |
var ppts = []; | |
var i; | |
for(i=0; i<=h; i+=1){ | |
x = ( Math.sin(i / (h / 12)) * (h / 40) ) + (w / 2 ); | |
y = i; | |
ppts.push({x: x, y: y}); | |
} | |
ctx.beginPath(); | |
ctx.moveTo(ppts[0].x, ppts[0].y); | |
for (i=1; i < ppts.length - 2; i++) { | |
var c = (ppts[i].x + ppts[i + 1].x) / 2; | |
var d = (ppts[i].y + ppts[i + 1].y) / 2; | |
ctx.lineTo(ppts[i].x, ppts[i].y); | |
} | |
ctx.quadraticCurveTo( | |
ppts[i].x, | |
ppts[i].y, | |
ppts[i + 1].x, | |
ppts[i + 1].y | |
); | |
ctx.stroke(); | |
}); | |
}); | |
} | |
var throttled = throttle(checkTrails, 500); | |
$(window).resize(throttled); | |
checkTrails(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment