Bhupendra Jadeja
Bhupendra Jadeja

Reputation: 288

Change background of Canvas in Fabric JS

I am trying to change the background of Canvas. I am able to change the background of canvas but once i click on the background . It reload the original background and does not show the changed background. Hope you understand what i am trying to say. Following is the code which implementing to change the background.Based on select box,image will load

HTML

<div id="wrapper">
    <div class="canvas-container" style="float:left;">
        <canvas id="c" width="500" height="500" style="border:1px solid #ccc">     </canvas>
    </div>
</div>

<select id="color" class="styled-select">
    <option value="red">Red</option>
    <option value="green">Green</option>
    <option value="purple">Purple</option>
</select> 

SCRIPT

var canvas = new fabric.Canvas('c');
canvas.setBackgroundImage("red.png", canvas.renderAll.bind(canvas));
$('select#color').on('change', function() {
    var imageName=this.value+".png"
    var canvas = new fabric.Canvas('c');
    canvas.setBackgroundImage(imageName, canvas.renderAll.bind(canvas));
})

Upvotes: 1

Views: 3719

Answers (1)

ptCoder
ptCoder

Reputation: 2247

Welcome to Stack overflow!

You have two times var canvas = new fabric.Canvas('c');. Remove last.

To change background color you only need canvas.backgroundColor property:

$('select#color').on('change', function() {
    canvas.backgroundColor = this.value;
    canvas.renderAll();
});

I have created a fiddle for this: http://jsfiddle.net/q6Y6k/15/

I hope this helps.

Upvotes: 3

Related Questions