我想更改矩形度量,并在高度和宽度的形式中输入值。但函数重新计算(inputWidth,inputHeight)失败。任何人都可以帮助我吗?
这是我的HTML代码:
<div class="row">
<div class="col-sm-3">
<form>
<div class="form-group">
<label for="inputHeight">Height</label>
<input type="text" name="inputHeight" class="form-control">
</div>
<div class="form-group">
<label for="inputWidth">Width</label>
<input type="text" name="inputWidth" class="form-control">
</div>
<button onclick="recalculate(inputWidth, inputHeight)" type="submit" class="btn btn-primary squareP">Modify Rectangle</button>
<button type="button" class="btn btn-primary square">Rectangle</button>
</form>
</div>
<div class="col-sm-9">
<canvas id="myCanvas"></canvas>
</div>
这是javascript:
var canvas = new fabric.Canvas('myCanvas', {
width: window.innerWidth,
height: window.innerWidth - 50,
isDrawingMode: false,
backgroundColor: '#fff'
});
document.querySelectorAll('.square')[0].addEventListener('click', function() {
var rect = new fabric.Rect({
top: 100,
left: 100,
width: 100,
height: 100,
fill: '',
selection: false,
fill: '#f55'
});
canvas.add(rect);
});
document.body.querySelectorAll('.squareP')[0].addEventListener('click', function recalculate(inputWidth, inputHeight) {
var obj = canvas.getActiveObject();
obj.set('width', inputWidth).set('height', inputHeight);
obj.set({width: inputWidth.value, height: inputHeight.value});
obj.setCoords();
canvas.renderAll();
});
答案 0 :(得分:1)
有一个解决方案:jsfiddle
首先在您的HTML中,您必须删除表单标记,因为表单期望post属性起作用而您不需要它。然后删除函数的args,我们将使用JQuery。
<div class="row">
<div class="col-sm-3">
<div class="form-group">
<label for="inputHeight">Height</label>
<input type="text" name="inputHeight" class="form-control">
</div>
<div class="form-group">
<label for="inputWidth">Width</label>
<input type="text" name="inputWidth" class="form-control">
</div>
<button onclick="recalculate()" type="submit" class="btn btn-primary squareP">Modify Rectangle</button>
<button type="button" class="btn btn-primary square">Rectangle</button>
</div>
<div class="col-sm-9">
<canvas id="myCanvas"></canvas>
</div>
然后在你的JS中获取字段vlue并更新你的尺寸:
var canvas = new fabric.Canvas('myCanvas', {
width: window.innerWidth,
height: window.innerWidth - 50,
isDrawingMode: false,
backgroundColor: '#fff'
});
document.querySelectorAll('.square')[0].addEventListener('click', function() {
var rect = new fabric.Rect({
top: 100,
left: 100,
width: 100,
height: 100,
fill: '',
selection: false,
fill: '#f55'
});
canvas.add(rect);
});
document.body.querySelectorAll('.squareP')[0].addEventListener('click', function recalculate() {
var obj = canvas.getActiveObject();
var w = $("input[name='inputWidth']").val();
var h = $("input[name='inputHeight']").val();
obj.set('width', w).set('height', h);
obj.setCoords();
canvas.renderAll();
});
请注意,编辑对象高度和宽度时,不要更改边框位置(请检查小提琴上的位置)。如果你想要这种行为,最好使用scale。