基于使用VueJS窗口变化调整画布元素

问题描述 投票:1回答:1

我想一个canvas元素的大小调整为使用VueJS窗口的宽度。我已经看到了香草JS工作的许多这样的例子,但因为种种原因,与VueJS我不能让画布内容重新呈现。

一个例子是附接。这个例子是从这里的香草JS版本修改:http://ameijer.nl/2011/08/resizable-html5-canvas/

https://codepen.io/bastula/pen/yZXowo

<!DOCTYPE html>
<html lang="en">

<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <title>Canvas Test</title>
</head>

<body>
    <div id="app">
        <canvas id="image-canvas" ref="imagecanvas" v-bind:width="width" v-bind:height="height" style="
            background-color: #000;">
        </canvas>
    </div>
</body>

</html>

<script type="text/javascript" src="https://unpkg.com/vue"></script>
<script>
    const app = new Vue({
        el: '#app',
        data: function () {
            return {
                height: 512,
                width: 512,
                margin: 20,
            };
        },
        mounted() {
            window.addEventListener('resize', this.handleResize);
            this.handleResize();
        },
        computed: {
            canvas: function () {
                return this.$refs.imagecanvas;
            },
            ctx: function () {
                return this.canvas.getContext('2d');
            }
        },
        methods: {
            handleResize: function () {
                // Calculate new canvas size based on window
                this.height = window.innerHeight - this.margin;
                this.width = window.innerWidth - this.margin;
                this.drawText();
            },
            drawText: function () {
                // Redraw & reposition content
                var resizeText = 'Canvas width: ' + this.canvas.width + 'px';
                this.ctx.textAlign = 'center';
                this.ctx.fillStyle = '#fff';
                this.ctx.fillText(resizeText, 200, 200);
            }
        },
        beforeDestroy() {
            window.removeEventListener('resize', this.handleResize);
        }
    })
</script>
html5 vue.js html5-canvas
1个回答
0
投票

这里解决:https://forum.vuejs.org/t/resize-canvas-element-based-on-window-change-using-vuejs/55497/2?u=bastula

该解决方案是使用:nextTick

因此,而不是在this.drawText()方法handleResize它应该是:

this.$nextTick(() => {
    this.drawText();
})

更新工作CodePen可以发现here

© www.soinside.com 2019 - 2024. All rights reserved.