javascript class image.onload

2k views Asked by At

I`m work at one draw layer, that i need to make Javascript class that will draw image on canvas. Now i have some like this:

    <canvas id="stage" width="1000" height="640"></canvas>
    <script>
        function ImageD(canvasId, imageSRC, X, Y, widht, height, Opacity)
        {
            var canvas;
            var canvasInfo;
            var opacity = Opacity || 1;
            var image = new Image();

            var selectCanvas = function()
            {
                canvas = document.getElementById(canvasId);
            };

            var get2dContext = function()
            {
                canvasInfo = canvas.getContext("2d");
            };

            this.draw = function()
            {
                selectCanvas();
                get2dContext();
                image.onLoad = function()
                {
                    canvasInfo.drawImage(image, X, Y);
                };
                image.src = imageSRC;
            };
        }

        var img = new ImageD("stage",      "http://www.nasa.gov/images/content/711375main_grail20121205_4x3_946-710.jpg", 20, 20, 30, 30);
img.draw();
    </script>

and at console i got this error or notice...

Resource interpreted as Script but transferred with MIME type text/plain: .....

1

There are 1 answers

0
user3088870 On

I repair this with follow code:

    function ImageD(canvasId, imageSRC, X, Y, widht, height, Opacity)
{
    var canvas;
    var canvasInfo;
    var opacity = Opacity || 1;
    var image = new Image();

    var selectCanvas = function()
    {
        canvas = document.getElementById(canvasId);
    };

    var get2dContext = function()
    {
        canvasInfo = canvas.getContext("2d");
    };

    var drawImg = function()
    {
        canvasInfo.drawImage(image, X, Y);
    };

    this.draw = function()
    {
        selectCanvas();
        get2dContext();
        image.src = imageSRC;
        image.addEventListener('load', drawImg, false);
    };
}