setBackgroundColor examples

Used in documentation (jsdoc tag)

by 20yco

HTML

<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="400" height="400"></canvas>
<button id="toggle-repeat">Toggle repeat</button>
<button id="toggle-bgcolor">Toggle background</button>
<button id="set-gradient">Set Gradient</button>

CSS

canvas {
    border: 1px solid #999;
}
button {
    margin-top: 20px;
}

JavaScript

// Do some initializing stuff
fabric.Object.prototype.set({
    transparentCorners: false,
    cornerColor: 'rgba(102,153,255,0.5)',
    cornerSize: 12,
    padding: 5
});

// initialize fabric canvas and assign to global windows object for debug
var canvas = window._canvas = new fabric.Canvas('c');

canvas.setBackgroundColor({source: 'http://fabricjs.com/assets/escheresque_ste.png'}, canvas.renderAll.bind(canvas));

fabric.util.addListener(document.getElementById('toggle-repeat'), 'click', function () {
    if (!canvas.backgroundColor instanceof fabric.Pattern) return;
    
    canvas.backgroundColor.repeat = canvas.backgroundColor.repeat === 'repeat' 
        ? 'repeat-x'
        : canvas.backgroundColor.repeat === 'repeat-x'
            ? 'repeat-y'
            : canvas.backgroundColor.repeat === 'repeat-y'
                ? 'no-repeat'
                : 'repeat';

    canvas.renderAll();
});

fabric.util.addListener(document.getElementById('toggle-bgcolor'), 'click', function () {
    if (canvas.backgroundColor instanceof fabric.Pattern) {
        canvas.setBackgroundColor('rgba(255, 73, 64, 0.6)', canvas.renderAll.bind(canvas));
    }
    else {
        canvas.setBackgroundColor({source: 'http://fabricjs.com/assets/escheresque_ste.png'}, canvas.renderAll.bind(canvas));        
    }
});

fabric.util.addListener(document.getElementById('set-gradient'), 'click', function () {
    
var grad = new fabric.Gradient({
    type: 'linear',
    coords: {
        x1: 0,
    y1: 0,
    x2: canvas.width,
    y2: canvas.height,
    },
    colorStops: [
    {
        color: 'rgb(166,111,213)',
        offset: 0,
    },
    {
        color: 'rgba(106, 72, 215, 0.5)',
        offset: 0.5,
    },
    {    
        color: '#200772',
        offset: 1,
    }
    ]});
canvas.backgroundColor = grad.toLive(canvas.contextContainer);
    canvas.renderAll();
});