Skip to content

Instantly share code, notes, and snippets.

@ap1969
Created July 22, 2021 09:28
Show Gist options
  • Save ap1969/02f074c6ff58d1d37fcc531e779d14ea to your computer and use it in GitHub Desktop.
Save ap1969/02f074c6ff58d1d37fcc531e779d14ea to your computer and use it in GitHub Desktop.
Using snap-svg in Vue 3
<template>
<q-page class="flex flex-center">
<div>
<svg id="svg" width="300" height="300"></svg>
</div>
<svg width="0" height="0">
<pattern
id="pattern"
patternUnits="userSpaceOnUse"
x="0"
y="0"
width="10"
height="10"
viewBox="0 0 10 10"
>
<path d="M-5,0,10,15M0-5,15,10" stroke="white" stroke-width="5" />
</pattern>
</svg>
</q-page>
</template>
<script>
import { defineComponent } from "vue";
export default defineComponent({
name: "PageIndex",
data() {
return {
snap: null,
};
},
mounted: function () {
let self = this;
const s = document.createElement("script");
s.type = "text/javascript";
s.src =
"https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.5.1/snap.svg-min.js";
s.onload = function () {
console.log("Snap is loaded");
self.snap = Snap("#svg");
self.init();
};
document.body.appendChild(s);
},
methods: {
init() {
const bigCircle = this.snap.circle(150, 150, 100);
bigCircle.attr({
fill: "#bada55",
stroke: "#000",
strokeWidth: 5,
});
// Now lets create another small circle:
var smallCircle = this.snap.circle(100, 150, 70);
// Lets put this small circle and another one into a group:
var discs = this.snap.group(smallCircle, this.snap.circle(200, 150, 70));
// Now we can change attributes for the whole group
discs.attr({
fill: "#fff",
});
// Now more interesting stuff
// Lets assign this group as a mask for our big circle
bigCircle.attr({
mask: discs,
});
// Despite our small circle now is a part of a group
// and a part of a mask we could still access it:
smallCircle.animate({ r: 50 }, 1000);
// We don’t have reference for second small circle,
// but we could easily grab it with CSS selectors:
discs.select("circle:nth-child(2)").animate({ r: 50 }, 1000);
// Now lets create pattern
var p = this.snap.path("M10-5-10,15M15,0,0,15M0-5-20,15").attr({
fill: "none",
stroke: "#bada55",
strokeWidth: 5,
});
// To create pattern,
// just specify dimensions in pattern method:
p = p.pattern(0, 0, 10, 10);
// Then use it as a fill on big circle
bigCircle.attr({
fill: p,
});
// We could also grab pattern from SVG
// already embedded into our page
discs.attr({
fill: Snap("#pattern"),
});
// Lets change fill of circles to gradient
// This string means relative radial gradient
// from white to black
discs.attr({ fill: "r()#fff-#000" });
// Note that you have two gradients for each circle
// If we want them to share one gradient,
// we need to use absolute gradient with capital R
discs.attr({ fill: "R(150, 150, 100)#fff-#000" });
},
},
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment