我正在尝试通过Vue控件更新Fabricjs画布。我正在通过‘挂载()’初始化画布,但不知道如何在函数中访问画布而不将画布作为参数传递。
这是我的困境的一个例子。我想要按钮调整圆圈的大小。
HTML:
<div id="app">
<a href="#" @click="resize()">RESIZE</>
<canvas id="c"></canvas>
</div>
联署材料:
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对象可以从这样的函数访问的最佳方法是什么?
发布于 2021-02-21 16:19:13
看起来,下一个调整代码大小的部分不起作用。但是为了帮助您解决canvas.getObjects()返回未定义的问题。
您需要做的是,在使用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就会被定义。然而,你的调整没有工作,所以你只需要克服那个驼峰,你就离开了!
#注:我试图改变你圆的高度,而不是半径
https://stackoverflow.com/questions/66308492
复制相似问题