Draw image in canvas with JQuery

$.fn.colorPicker = function () {
    const $div = this;
    const $colorPickerIcon = $("<img></img");
    const $canvas = $("<canvas></canvas>").addClass("canvas");
    const $context = $canvas.getContext("2d");
    const $closeButton = new Image();
    $closeButton.src = "./imgs/close.png";
    $($colorPickerIcon).attr("src", "./imgs/icon.jpg").attr("id", "icon").appendTo($div);
    $($colorPickerIcon).on("click", function () {
        $($colorPickerIcon).hide();
        $($closeButton).on("load", function () {
            $context.drawImage($closeButton, 0, 0);
        });
    });
}

I tried this code and after many changes I decide to question for solution here. I have a problem with getting context. I always recieve this mistake "TypeError: $canvas.getContext is not a function". I used this article to program this, but it's still not working.

Upvotes: 0

Views: 1506

Answers (1)

Tom M
Tom M

Reputation: 2904

You are trying to access the getContext-Method of a jQuery Object. But getContext is a method of HTMLCanvasElement which is accessible under $('<canvas></canvas>')[0].getContext("2d")

Upvotes: 2

Related Questions