使用 VueJS 根据 window 更改调整 canvas 元素的大小

Resize canvas element based on window change using VueJS

我正在尝试使用 VueJS 将 canvas 元素的大小调整为 window 的宽度。我已经看到很多使用 vanilla JS 的示例,但是无论出于何种原因,使用 VueJS 我都无法重新渲染 canvas 内容。

附上例子。该示例是从此处的 vanilla 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>

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

解决方案是使用:nextTick.

所以 handleResize 方法中的 this.drawText() 应该是:

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

可以找到更新的工作 CodePen here