Quick Start with Fabric.js: Building a Canvas App in Vue
This guide introduces Fabric.js—a library that adds an object model, SVG parsing, and interactivity to HTML5 Canvas—and walks through setting up a Vue project, installing the library, creating a canvas element, and drawing a red rectangle with concise code examples.
Fabric.js is a JavaScript library that simplifies Canvas programming by providing a missing object model, an SVG parser, interaction support, and a suite of essential tools.
To try it, first create a Vue project (the article references a tutorial for setting up a Vue environment) and install Fabric.js with: npm install fabric --save In a Vue component, add a <canvas> element with a fixed size and an id of c:
<template>
<canvas id="c" width="800" height="800"></canvas>
</template>Import the library in the script section and initialize the canvas after the component mounts:
import { fabric } from 'fabric';
export default {
name: "HelloFabric",
mounted() {
this.init();
},
methods: {
init() {
// create a wrapper around the native canvas element (id="c")
var canvas = new fabric.Canvas('c');
// create a rectangle object
var rect = new fabric.Rect({
left: 100, // distance from the left edge in pixels
top: 100, // distance from the top edge in pixels
fill: 'red', // fill color
width: 20, // rectangle width
height: 20 // rectangle height
});
// add the rectangle onto the canvas
canvas.add(rect);
}
}
};The resulting canvas displays a red square at the specified coordinates, as shown in the following screenshot:
For reference, the complete component code (template, script, and initialization) is provided below:
<template>
<canvas id="c" width="800" height="800"></canvas>
</template>
<script>
import { fabric } from 'fabric';
export default {
name: "HelloFabric",
mounted() {
this.init();
},
methods: {
init() {
var canvas = new fabric.Canvas('c');
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'red',
width: 20,
height: 20
});
canvas.add(rect);
}
}
};
</script>This short example demonstrates how Fabric.js can turn low‑level Canvas APIs into concise, object‑oriented code within a modern front‑end framework.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
The Dominant Programmer
Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
