如何选择颜色,将其填充到使用fabric.js在画布中上传的选定图像中?

时间:2017-07-01 08:45:39

标签: javascript html canvas html5-canvas fabricjs

我有这个项目,其中一个要求是在画布中自定义和设计上传的图像 。因此,通过自定义,我将上传图像,选择它,我想用所选颜色更改颜色或着色。但是我不知道怎么做。

var canvas = new fabric.Canvas('canvas');
        var clearEl = document.getElementById('clear');
        var reset = document.getElementById('Reset');
        clearEl.onclick = function ()
        {
            canvas.clear()
        };
        reset.onclick = function () {
            window.location.reload();
        };
        document.getElementById('file').addEventListener("change", function (e) {
            var file = e.target.files[0];
            var reader = new FileReader();
            console.log("reader   " + reader);
            reader.onload = function (f) {
                var data = f.target.result;
                fabric.Image.fromURL(data, function (img) {
                    var oImg = img.set({ left: 70, top: 100, width: 250, height: 200, angle: 0 }).scale(0.9);
                    canvas.add(oImg).renderAll();
                    canvas.setActiveObject(oImg);
                });
            };
            reader.readAsDataURL(file);
        });

        $('#fill').change(function () {
            var obj = canvas.getActiveObject();
            if (obj) {
                obj.setFill($(this).val());
            }
            canvas.renderAll();
        });

        $('#font').change(function () {
            var obj = canvas.getActiveObject();
            if (obj) {
                obj.setFontFamily($(this).val());
            }
            canvas.renderAll();
        });

        function addText() {
            var oText = new fabric.IText('Tap and Type', {
                left: 100,
                top: 100,
            });

            canvas.add(oText);
            canvas.setActiveObject(oText);
            $('#fill, #font').trigger('change');
            oText.bringToFront();
        }

        document.querySelector('#txt').onclick = function (e) {
            e.preventDefault();
            canvas.deactivateAll().renderAll();
            document.querySelector('#preview').src = canvas.toDataURL();
        };
$("#saveImg").click(function(){
            $("#canvas").get(0).toBlob(function(blob){ 
                saveAs(blob, uuidv4());
               
        });
        });
canvas{
border:1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
            <script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
            <input type="file" id="file">
            <input type="color" value="blue" id="fill" />
            <input type="checkbox" id=tint />
            Tint:
              <input type="color" value="blue" id="fillimage" />
            <select id="font">
                <option>arial</option>
                <option>tahoma</option>
                <option>times new roman</option>
            </select>
            <button onclick="addText(); return false;">Add Custom Text</button>
                 <input type="button" value="Clear Canvas" id="clear" />
              <input type="button" value="Reset" id="Reset" />
             <input type="button" id="saveImg" value="Save Image"/>
            <br />
            <canvas id="canvas" width="600" height="400"></canvas>
            <br />
             

            <a href='' id='txt' target="_blank">Preview Image</a>
            <br />
            <img id="preview" />

1 个答案:

答案 0 :(得分:1)

以下代码提供了您尝试实现的功能的基本演示:

var canvas = new fabric.Canvas('canvas');
var clearEl = document.getElementById('clear');
var reset = document.getElementById('Reset');
clearEl.onclick = function ()
{
    canvas.clear();
};
reset.onclick = function () {
    window.location.reload();
};
document.getElementById('file').addEventListener("change", function (e) {
    var file = e.target.files[0];
    var reader = new FileReader();
    console.log("reader   " + reader);
    reader.onload = function (f) {
        var data = f.target.result;
        fabric.Image.fromURL(data, function (img) {
            var oImg = img.set({ left: 70, top: 100, width: 250, height: 200, angle: 0 }).scale(0.9);
            canvas.add(oImg).renderAll();
            canvas.setActiveObject(oImg);
        });
    };
    reader.readAsDataURL(file);
});

$('#fill').change(function () {
    var obj = canvas.getActiveObject();
    if (obj) {
        obj.setFill($(this).val());
    }
    canvas.renderAll();
});

$('#font').change(function () {
    var obj = canvas.getActiveObject();
    if (obj) {
        obj.setFontFamily($(this).val());
    }
    canvas.renderAll();
});

// Listen for changes in UI
$('#tint').change(function() {
    // Get the selected colour
    var tintHex = $('#fillimage').val();

    if ($(this).is(':checked') === true) {
        applyTint(tintHex);
    } else {
        removeTint();
    }
});

// Apply Tint filter
function applyTint (tintHex) {
    // Get active object
    var object = canvas.getActiveObject();

    if (!object) {
        console.error('No image selected');
        return false;
        // Could prompt the user to select an image, or programmatically do it for them
    }

    // Apply the tint. Based on docs at: http://fabricjs.com/docs/fabric.Image.filters.Tint.html#initialize
    var tintFilter = new fabric.Image.filters.Tint({
        color: tintHex,
        //opacity: 0.5 // Could also pass in an opacity value
    });
    object.filters.push(tintFilter);
    object.applyFilters(canvas.renderAll.bind(canvas));
}

// Remove Tint filter
function removeTint () {
    // Get active object
    var object = canvas.getActiveObject();

    if (!object) {
        console.error('No image selected');
        return false;
        // Could prompt the user to select an image, or programmatically do it for them
    }

    object.filters = []; // Empty filters array
    object.applyFilters(canvas.renderAll.bind(canvas));
}

function addText() {
    var oText = new fabric.IText('Tap and Type', {
        left: 100,
        top: 100,
    });

    canvas.add(oText);
    canvas.setActiveObject(oText);
    $('#fill, #font').trigger('change');
    oText.bringToFront();
}

document.querySelector('#txt').onclick = function (e) {
    e.preventDefault();
    canvas.deactivateAll().renderAll();
    document.querySelector('#preview').src = canvas.toDataURL();
};
$("#saveImg").click(function(){
    $("#canvas").get(0).toBlob(function(blob){ 
        saveAs(blob, uuidv4());
       
});
});
canvas{
  border:1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
<input type="file" id="file">
<input type="color" value="blue" id="fill" />
<input type="checkbox" id=tint />
Tint:
  <input type="color" value="blue" id="fillimage" />
<select id="font">
    <option>arial</option>
    <option>tahoma</option>
    <option>times new roman</option>
</select>
<button onclick="addText(); return false;">Add Custom Text</button>
     <input type="button" value="Clear Canvas" id="clear" />
  <input type="button" value="Reset" id="Reset" />
 <input type="button" id="saveImg" value="Save Image"/>
<br />
<canvas id="canvas" width="600" height="400"></canvas>
<br />
 

<a href='' id='txt' target="_blank">Preview Image</a>
<br />
<img id="preview" />

主要变化:

  • 为Fabric JS库使用不同的CDN。您链接到的Fabric JS库的版本在尝试创建Tint过滤器时导致错误。
  • 使用jQuery侦听对复选框状态的更改并调用新函数以应用或删除色调过滤器
  • N.B。请务必使用半透明PNG图像测试示例,以查看正在运行的色调