javascript类image.onload

时间:2013-12-10 23:02:34

标签: javascript html5 canvas onload-event

我在一个绘图层工作,我需要制作将在画布上绘制图像的Javascript类。现在我有一些这样的:

    <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>

在控制台我收到此错误或通知......

资源解释为脚本,但使用MIME类型text / plain传输:.....

1 个答案:

答案 0 :(得分:0)

我使用以下代码修复此问题:

    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);
    };
}