从Vue方法更新FabricJS对象



我试图通过Vue控件更新Fabricjs画布。我通过'mounted()'初始化画布,但不知道如何在函数中访问画布,而不将画布作为参数传递。

这是我的困境的一个例证。我想让按钮调整圆圈的大小。

HTML:

<div id="app">
<a href="#" @click="resize()">RESIZE</>
<canvas id="c"></canvas>
</div>

JS:

new Vue({
el: "#app",
data: {
title: "Default title",
message: null,
canvas: null
},
mounted() {
const canvas = new fabric.Canvas("c", {
width: 500,
height: 500
});
this.canvas = canvas;
this.loadCir(canvas);
},
methods: {
loadCir(canvas) {
const cir = new fabric.Circle({
fill: "red",
radius: 50,
top: 10,
left: 10
});
cir.name = "circle";
canvas.add(cir);
},
resize() {
this.canvas.getObjects().forEach(function (targ) {
if (targ.name == "circle") {
targ.radius = 100;
}
});
}
}
});

https://codepen.io/shnlmn/pen/JjbrKNL

这个脚本的结果是:
TypeError: Cannot read property 'getObjects' of undefined

我觉得将画布存储到数据中不是一个好主意,但我不确定如何使其可访问到应用程序的其余部分。

使Fabricjs对象从这样的函数访问的最好方法是什么?

看起来下一个调整代码大小的部分不工作。但是为了帮助您解决canvas.getObjects()返回undefined的问题。

你需要做的是当使用data属性时,你只需要确保所有东西都引用了data属性。您创建变量并将其保存到数据属性,这是不需要的,您可以在this.canvas

上完成所有工作
new Vue({
el: "#app",
data: {
title: "Default title",
message: null,
canvas: null
},
mounted() {
this.canvas = new fabric.Canvas("c", {
width: 500,
height: 500
});
this.canvas.getContext('2d');
this.loadCir();
},
methods: {
loadCir() {
const cir = new fabric.Circle({
fill: "red",
radius: 50,
top: 10,
left: 10
});
cir.name = "circle";
this.canvas.add(cir);
},
resize() {
this.canvas.getObjects().forEach(function (targ) {
if (targ.name == "circle") {
targ.height = 100;
}
});
}
}
});

一旦你在任何地方引用this.canvas并实际做你的数据属性的工作,那么你的getObjects被定义。然而,你的调整大小不起作用,所以你只需要克服这个困难,你就可以离开了!

注意:我试图改变你的圆的高度,而不是半径

最新更新