// create a wrapper around native canvas element (with id="c")
var canvas = new fabric.Canvas('c')
var render_callback = canvas.renderAll.bind(canvas)
// create a rectangle object
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'red',
width: 20,
height: 20
});
// "add" rectangle onto canvas
canvas.add(rect);
// ========================================
// Canvas object event handlers
rect.on('btn1_click', function(e) {
console.log('custom event #1', e.data);
// Change the fill color and re-add the object
rect.set('fill', e.data)
canvas.add(rect);
});
canvas.on('btn2_click', function(e) {
console.log('custom event #2', e.data);
// Set a background image,
// the callback (2nd argument) is needed to re-render
canvas.setBackgroundImage(e.data, render_callback)
});
// ========================================
// DOM event handlers for the buttons
$("#change_color").on("click", function(){
console.log($(this).data("color"))
// Fire the canvas event and pass the image url
rect.fire("btn1_click", {data: $(this).data("color")})
})
$("#change_image").on("click", function(){
console.log($(this).data("img"))
// Fire the canvas event and pass the image url
canvas.fire("btn2_click", {data: $(this).data("img")})
})
#c{
border: 1px solid lightgrey;
}
button{
margin: 2em 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.3.0/fabric.min.js"></script>
<canvas id="c" width=220 height=220></canvas>
<button id="change_color" data-color="blue">Click me to change the rect color</button>
<button id="change_image" data-img="https://via.placeholder.com/220x220.png">Click me to add an image</button>