Skip to content

Instantly share code, notes, and snippets.

@subzey
Last active December 10, 2020 17:50
Show Gist options
  • Save subzey/822b901f2bbd9c4b05dbf704e7677c35 to your computer and use it in GitHub Desktop.
Save subzey/822b901f2bbd9c4b05dbf704e7677c35 to your computer and use it in GitHub Desktop.
Svg use & canvas path2d
<html>
<head>
<style>
svg, canvas { outline: black 1px dotted }
</style>
</head>
<body>
<h2>SVG &lt;use&gt;</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>
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment