Last active
December 10, 2020 17:50
Star
You must be signed in to star a gist
Svg use & canvas path2d
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
<html> | |
<head> | |
<style> | |
svg, canvas { outline: black 1px dotted } | |
</style> | |
</head> | |
<body> | |
<h2>SVG <use></h2> | |
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="100" width="120"><use xlink:href="tv-heart.svg#heart"/></svg> | |
<h2>Canvas Path2D</h2> | |
<canvas height="100" width="120"></canvas> | |
<script> | |
const svg = document.querySelector('svg'); | |
requestAnimationFrame(function frame(now) { | |
svg.style.color = `hsl(${ (now / 10) % 360 }, 100%, 50%)`; | |
svg.style.transform = `rotate(${ now / 100}deg)`; | |
requestAnimationFrame(frame); | |
}); | |
(async function() { | |
const res = await fetch('tv-heart.svg'); | |
if (!res.ok) { throw new Error('pas glop!'); } | |
const doc = new DOMParser().parseFromString(await res.text(), "text/xml"); | |
const el = doc.querySelector('#heart path'); | |
const path2d = new Path2D(el.getAttribute('d')); | |
const ctx = document.querySelector('canvas').getContext('2d'); | |
requestAnimationFrame(function frame(now) { | |
ctx.save(); | |
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); | |
ctx.translate(ctx.canvas.width / 2, ctx.canvas.height / 2); | |
ctx.rotate(now / 100 / 360 * 2 * Math.PI); | |
ctx.translate(-ctx.canvas.width / 2, -ctx.canvas.height / 2); | |
ctx.fillStyle = `hsl(${ (now / 10) % 360 }, 100%, 50%)`; | |
ctx.fill(path2d); | |
ctx.restore(); | |
requestAnimationFrame(frame); | |
}); | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment