如何在模板中组织画布脚本

how organize canvas script in template

本文关键字:布脚本 脚本      更新时间:2023-09-26

如何将画布脚本分离为助手?目前,它只有在直接写入模板本身的情况下才有效。我想这很琐碎,但我不知道怎么做。谢谢!(scaledPrite也是一个助手)

<template name="spriteBox">
    <script>
        var myImage = new Image();
        myImage.src="{{ spirte.url store='OriginalPix' }}";
        myImage.onload = function() {
            var c = document.getElementById("myCanvas");
            var ctx = c.getContext("2d");
            ctx.fillStyle = "{{ sprite.metadata.backColor }}";
            ctx.fillRect(0, 0, {{ scaledSprite.widthDevice }}, {{ scaledSprite.heightDevice }});
            ctx.imageSmoothingEnabled = false;
            ctx.drawImage(myImage, 0, 0, {{ scaledSprite.widthDevice }}, {{ scaledSprite.heightDevice }});
        }
    </script>
    <canvas id="myCanvas" width="{{ scaledSprite.widthDevice }}" height="{{ scaledSprite.heightDevice }}" style="width:{{ scaledSprite.width }}px; height: {{ scaledSprite.height }}px;">
        This browser does not support HTML5 canvas
    </canvas>
</template>

这不起作用:尝试分离脚本并将其移动到spriteBox.js:

Template.spriteBox.rendered = function () {
    var myImage = new Image();
    myImage.src= this.sprite.url;
        // > Exception from Tracker afterFlush function: Cannot read property 'url' of undefined
        // > TypeError: Cannot read property 'url' of undefined
    myImage.onload = function() {
        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d");
        ctx.fillStyle = this.sprite.metadata.backColor;
        ctx.fillRect(0, 0, scaledSprite.widthDevice, scaledSprite.heightDevice);
        ctx.imageSmoothingEnabled = false;
        ctx.drawImage(myImage, 0, 0, scaledSprite.widthDevice, scaledSprite.heightDevice);
    }
};

HTML

<template name="spriteBox">
    <canvas id="myCanvas" width="{{ scaledSprite.widthDevice }}" height="{{ scaledSprite.heightDevice }}" style="width:{{ scaledSprite.width }}px; height: {{ scaledSprite.height }}px;">
        This browser does not support HTML5 canvas
    </canvas>
</template>

铁路由器

Router.route('/spriteBox/:_id/:boxsize', {
    name: 'spriteBox',
    template: 'spriteBox',
    waitOn: function() {
        return [
            subs.subscribe('aPix', this.params._id)
        ];
    },
    data: function() {
        var spriteDocument = MyPix.findOne({_id: this.params._id});
        templateData = {
            sprite: spriteDocument,
        }
        return templateData;
    }
});

渲染函数的一个明显错误是不能在javascript代码中使用{…}。这只是用于模板。您需要直接调用实际的函数。

基于您的新代码,您有一个新错误:

myImage.src= this.sprite.url;

应该是

myImage.src= this.data.sprite.url;