New to Telerik UI for ASP.NET MVC? Download free 30-day trial

Implementing Eyedropper Functionality for the ImageEditor

Environment

Product Version
Product ImageEditor for ASP.NET MVC

Description

How can I create a custom tool to pick a color from an image in the ImageEditor when working with the Telerik UI for ASP.NET MVC components?

Solution

The MDN tutorial for extracting data from a canvas element demonstrates how to extract the color for a specific pixel. Add a custom command to the ImageEditor Toolbar implementing the logic demonstrated in the MDN tutorial linked above.

In the example below, clicking on the image retrieves the color of the pixel clicked and sets it as the value of the ColorPicker component. Inspect this runnable example of the code snippet below:

 <script>

     function pick(event, canvas, ctx) {
        const bounding = canvas.getBoundingClientRect();
        const x = event.clientX - bounding.left;
        const y = event.clientY - bounding.top;
        const pixel = ctx.getImageData(x, y, 1, 1);
        const data = pixel.data;

        const rgba = `rgba(${data[0]}, ${data[1]}, ${data[2]}, ${data[3] / 255})`;

        return data
    }
        var imageEditorNS = kendo.ui.imageeditor;

        imageEditorNS.commands.GetColorImageEditorCommand = imageEditorNS.ImageEditorCommand.extend({
        exec: function () {
            var that = this,
                options = that.options,
                imageeditor = that.imageeditor,
                canvas = imageeditor.getCanvasElement(),
                ctx = imageeditor.getCurrent2dContext(),
                image = imageeditor.getCurrentImage();

            canvas.addEventListener("click", function(event){
                var data = pick(event, canvas, ctx);
                var picker = $("#colorpicker").getKendoColorPicker();
                picker.value(`rgba(${data[0]},${data[1]},${data[2]},${data[3] / 255})`);
                picker.trigger("change")
            },{once : true});
        }
        });
    </script>
<div class="demo-section wide">
    <label>Selected Color:</label>
     @(Html.Kendo().ColorPicker()
          .Name("colorpicker")
    )
    <h3>Upload image and select color:</h3>
    @(Html.Kendo().ImageEditor()
        .Name("imageEditor")
        .Height(900)
        .Toolbar(toolbar=>toolbar.Items(i=> {
            i.Add().Name("open");
            i.Add().Command("GetColorImageEditorCommand").Type("button").Text("Get Color").Icon("eyedropper");
        }))
    )
</div>

More ASP.NET MVC Editor Resources

See Also

In this article