Closed sefatanam closed 2 weeks ago
To integrate canvas-sketch into your framework, follow these steps:
Reference the Canvas Element: First, obtain a reference to the canvas element in your component code.
Create a Settings Object: Define a settings object to configure your canvas ([more on settings](https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md#props)). For example:
const settings = {
dimensions: [2048, 2048],
styleCanvas: true,
units: "px",
scaleToView: true,
canvas: canvas, // Reference to your canvas element
resizeCanvas: true,
};
Render the Canvas:
Finally, call the canvasSketch
([more on canvasSketch](https://github.com/mattdesl/canvas-sketch/blob/master/docs/hello-world.md))function to render the canvas with the specified settings. For my design system I had to use
#canvas {
max-height: 500px !important;
max-width: 500px !important;
}
<script lang="ts">
//@ts-ignore
import canvasSketch from "canvas-sketch";
import { onMount } from "svelte";
let canvas: HTMLCanvasElement;
let settings = {};
onMount(() => {
settings = {
dimensions: [2048, 2048],
styleCanvas: true,
units: "px",
scaleToView: true,
canvas: canvas,
resizeCanvas: true,
};
canvasSketch(
// @ts-ignore
({ context, canvasHeight, canvasWidth, ...args }) => {
return () => {
// YOUR_ART_WORK_GOES HERE
};
},
{ ...settings, canvas }
);
});
</script>
<canvas bind:this={canvas} id="canvas"></canvas>
<style>
#canvas {
max-height: 500px !important;
max-width: 500px !important;
}
</style>
Thanks for sharing. Something else you’ll need to do is to make sure to call manager.destroy() when the component unmounts.
Resizing can sometimes be a little finicky as it wasn’t designed so well to be embedded within a svelte component. For example, if some part of your page changes the size of the parent without triggering a window resize event. One option is to set styleCanvas:false in settings, and then manually style the canvas as you see fit to fit the window. If you are doing this, you may also want to disable scaleToFit.
I'm trying to integrate canvas-sketch into a Svelte project but couldn't find any specific guidelines for integration into frameworks. The CLI documentation provides general information on building to a website, but I'm unsure how to adapt it for Svelte.
Has anyone successfully integrated canvas-sketch with Svelte? Any tips or examples would be greatly appreciated!