修改已返回的对象

时间:2014-12-29 07:39:37

标签: javascript html5 image canvas scope

编辑:感谢Teemu提供了很多帮助的答案

我不确定问题是否对我的问题说得非常正确......无论如何,我正在尝试创建一个用于我的html5游戏的getImage函数。我希望设计API,以便可以给出布尔预渲染参数。我在实现它时遇到问题,因此预渲染位可以修改返回的图像。

使用该函数的代码如下所示:

var resources = {
    image: getImage('path/to/my/image.png'),
    prerendered: getImage('my/prerendered/image.png', true)
};

getImage函数的代码如下所示:

var getImage = function (source, prerender) {
    var img = new Image(); // store as empty image

    img.onload = function () {
        if (prerender) { // all my prerendering code
            var can = document.createElement('canvas');
            var ctx = can.getContext('2d');

            can.width = img.width;
            can.height = img.height;

            ctx.drawImage(img, img.width, img.height);

            // right here is where I attempt to modify img
            // but since it's already been returned, I'm not changing the returned value - I think
            img = can;
        }

        img.ready = true; // a property my game uses to check if the resource is ready
    };

    img.src = source; // load that badboy

    return img;
};

我尝试过的一个解决方案是将img包装在一个对象中,并让它成为一个属性,例如

 var wrapper = {img: new Image()};

但这看起来很丑陋,我认为有更好的解决方案

2 个答案:

答案 0 :(得分:0)

我相信您可以使用canvas.toDataURL&将画布转换回图像。更新来源?

所以而不是:

img = can;

也许:

img.src = can.toDataURL();

答案 1 :(得分:0)

如果我已正确理解您的问题,您希望在canvasimg时返回prerender而不是true。如果是这样,你可以这样做:

var getImage = function (source, prerender) {
    var img = new Image(),
        can, ctx;
    img.onload = function () {
        if (prerender) {
            // prerender, can & ctx are defined in the outer scope
            // img still refers to the originally-created image, hence this will work
            can.width = img.width;
            can.height = img.height;
            ctx.drawImage(img, img.width, img.height);
        }
        img.ready = true;
    };
    if (prerender) {
        can = document.createElement('canvas');
        ctx = can.getContext('2d');
    }
    img.src = source;

    return can || img; // returns can if it's defined, img otherwise
};