2
votes

I've created a polymer element that needs a canvas 2d context as attribute to work, and I'm trying to get it from a sibling canvas tag.

I've seen https://www.polymer-project.org/1.0/docs/devguide/templates.html, but it doesn't answer my issue.

Here is what I have done for now:

<body>
<template id="app" is="dom-bind">
    <my-element id="renderer" context="{{ context }}"></my-element>
    <canvas id="rendering-canvas"></canvas>
</template>
<script>
    (function (document) {
        'use strict';
        var app = document.querySelector('#app');

        app.addEventListener('template-bound', function () {
            console.log('Our app is ready to rock!');
        });

        window.addEventListener('WebComponentsReady', function () {
            document.querySelector('body').removeAttribute('unresolved');

            var renderer = document.querySelector('my-element[id=renderer]'),
                canvas = document.querySelector('canvas[id=rendering-canvas]');

            app.context = canvas.getContext('2d');
        });
    })(document);
</script>
</body>

Edit: MyElement

Polymer({
        is : 'my-element',
        properties: {
            type: {
                type: String,
                value: 'Text'
            },
            context: {
                type: CanvasRenderingContext2D
            }
        }
    });

My main issue is how to to something like context="canvas.getContext('2d')" ? Right now the my-element's context property is not set.

1
Hi! @FXG who is context in your question (context="canvas.getContext('2d')? I'm using your code and my app.context is CanvasRenderingContext2D {}. Is not correct? - horacioibrahim
Also my-element.context is same (CanvasRenderingContext2D). - horacioibrahim
@horacioibrahim Yes, but this context is not passed as an attribute of my "my-element". I will edit my question to be more clear. - FXG
Polymer lists the following available types for properties: Boolean, Date, Number, String, Array or Object. So, I don't think that's going to work the way you have it currently. Maybe Object will work? - anthony
I've found it, it was a problem on my-element side. Changes to context property wasn't reflected because attributes using it was created on ready function. I've created an observer method and apply my changes here. It's working now. - FXG

1 Answers

2
votes
<my-element id="renderer"></my-element>
<canvas id="rendering-canvas"></canvas>

<script>
    (function (document) {
        'use strict';

        window.addEventListener('WebComponentsReady', function () {
            document.querySelector('body').removeAttribute('unresolved');

            var renderer = document.getElementById('renderer'),
                canvas = document.getElementById('rendering-canvas');

            renderer.context = canvas.getContext('2d');
        });
    })(document);
</script>