[英]Updating FabricJS objects from Vue method
我正在嘗試通過 Vue 控件更新 Fabricjs canvas。 I am initializing the canvas through 'mounted()', but do not know how to access the canvas in a function without passing the canvas as an argument.
這是我的困境的一個證明。 我想要按鈕來調整圓圈的大小。
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
我覺得將 canvas 存儲到數據中並不是一個好主意,但我不知道如何讓應用程序的 rest 可以訪問它。
使 Fabricjs 對象可從此類函數訪問的最佳方法是什么?
看起來您的代碼的下一個調整大小部分不起作用。 但是為了幫助您解決 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 就被定義了。 但是,您的調整大小不起作用,因此您只需要克服那個困難就可以了!
#note:我試圖改變你的圓的高度,而不是半徑
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.