|
| 1 | +const canvasSketch = require('canvas-sketch'); |
| 2 | +const d3 = require('d3'); |
| 3 | +const Random = require('canvas-sketch-util/random'); |
| 4 | +const Color = require('canvas-sketch-util/color'); |
| 5 | +const { linspace } = require('canvas-sketch-util/math'); |
| 6 | + |
| 7 | +const settings = { |
| 8 | + // For SVG to resize easily we will have to set this to true |
| 9 | + scaleToView: true, |
| 10 | + // Do not append <canvas> element |
| 11 | + parent: false, |
| 12 | + // Additional settings as desired |
| 13 | + dimensions: [ 512, 512 ] |
| 14 | +}; |
| 15 | + |
| 16 | +const sketch = ({ canvas, width, height }) => { |
| 17 | + // Create some random circle data |
| 18 | + const data = linspace(250).map(() => { |
| 19 | + const [ cx, cy ] = Random.insideCircle(width / 4) |
| 20 | + return { |
| 21 | + x: cx + width / 2, |
| 22 | + y: cy + height / 2, |
| 23 | + r: Math.max(1, Random.gaussian(width * 0.001, width * 0.02)), |
| 24 | + fill: Color.parse({ hsl: [ |
| 25 | + Random.range(140, 240), |
| 26 | + 50, |
| 27 | + 50 |
| 28 | + ] }).hex |
| 29 | + } |
| 30 | + }); |
| 31 | + |
| 32 | + // Create a svg element |
| 33 | + const svg = d3.select('body') |
| 34 | + .append('svg'); |
| 35 | + |
| 36 | + // Background |
| 37 | + svg.append('rect') |
| 38 | + .attr('x', 0) |
| 39 | + .attr('y', 0) |
| 40 | + .attr('width', width) |
| 41 | + .attr('height', height) |
| 42 | + .attr('fill', 'pink'); |
| 43 | + |
| 44 | + // Create circles from data |
| 45 | + svg |
| 46 | + .selectAll('circle') |
| 47 | + .data(data) |
| 48 | + .enter() |
| 49 | + .append('circle') |
| 50 | + .attr('cx', d => d.x) |
| 51 | + .attr('cy', d => d.y) |
| 52 | + .attr('fill', d => d.fill) |
| 53 | + .attr('r', d => d.r); |
| 54 | + |
| 55 | + return ({ exporting, width, height, styleWidth, styleHeight }) => { |
| 56 | + // First update the sizes to our viewport |
| 57 | + svg |
| 58 | + .attr('width', styleWidth) |
| 59 | + .attr('height', styleHeight) |
| 60 | + .attr('viewBox', `0 0 ${width} ${height}`); |
| 61 | + |
| 62 | + // If exporting, serialize SVG to Blob |
| 63 | + if (exporting) { |
| 64 | + // Clone the SVG element and resize to output dimensions |
| 65 | + const copy = d3 |
| 66 | + .select(svg.node().cloneNode(true)) |
| 67 | + .attr('width', width) |
| 68 | + .attr('height', height); |
| 69 | + |
| 70 | + // Make a blob out of the SVG and return that |
| 71 | + const data = svgToBlob(copy.node()); |
| 72 | + return { data, extension: '.svg' }; |
| 73 | + } |
| 74 | + }; |
| 75 | +}; |
| 76 | + |
| 77 | +canvasSketch(sketch, settings); |
| 78 | + |
| 79 | +function svgToBlob (svg) { |
| 80 | + const svgAsXML = new window.XMLSerializer().serializeToString(svg); |
| 81 | + return new window.Blob([ svgAsXML ], { type: 'image/svg+xml' }); |
| 82 | +} |
0 commit comments