因此,您实际上是在问两个问题:
1.我怎么知道什么时候文本框的值会改变?
您可以使用查找输入getElementById,并将更改附加到事件监听器event。
let widthInput = document.getElementById('width');
widthInput.addEventListener('change', (event) => {
});
2.如何在fabric.js中调整对象的大小
您可以在setFabric.js对象上使用该方法。然后renderAll在画布上调用。
rect.set('width', parseInt(widthInput.value));
canvas.renderAll();
全部一起:
注意:您必须单击文本框之外的内容才能触发更改事件。
https://jsfiddle.net/9v5zogju/
的HTML
我删除了无效的type属性,为每个输入提供了唯一的ID,并删除了多余的body标记。
Java脚本
我按原样保留了您的代码。我的代码在底部。
var canvas = new fabric.Canvas('canvas');
var grid = 20;
for (var i = 0; i < (800 / grid); i++) {
canvas.add(new fabric.Line([ i * grid, 0, i * grid, 800],
{strokeDashArray: [3, 17], strokeWidth : 3, stroke: 'black', selectable: false }));
canvas.add(new fabric.Line([ 0, i * grid, 800, i * grid],
{strokeDashArray: [3, 17], strokeWidth :3, stroke: 'black', selectable: false }))
}
var rect = new fabric.Rect({
top : 50,
left : 50,
width : 100,
height : 100,
fill : 'red',
hasControls : false
});
canvas.add(rect);
canvas.on('object:moving', function(options) {
options.target.set({
left: Math.round(options.target.left / grid) * grid,
top: Math.round(options.target.top / grid) * grid
});
});
canvas.on('object:moving', function (e) {
var obj = e.target;
// if object is too big ignore
if(obj.currentHeight > obj.canvas.height || obj.currentWidth > obj.canvas.width){
return;
}
obj.setCoords();
// top-left corner
if(obj.getBoundingRect().top < 0 || obj.getBoundingRect().left < 0){
obj.top = Math.max(obj.top, obj.top-obj.getBoundingRect().top);
obj.left = Math.max(obj.left, obj.left-obj.getBoundingRect().left);
}
// bot-right corner
if(obj.getBoundingRect().top+obj.getBoundingRect().height > obj.canvas.height || obj.getBoundingRect().left+obj.getBoundingRect().width > obj.canvas.width){
obj.top = Math.min(obj.top, obj.canvas.height-obj.getBoundingRect().height+obj.top-obj.getBoundingRect().top);
obj.left = Math.min(obj.left, obj.canvas.width-obj.getBoundingRect().width+obj.left-obj.getBoundingRect().left);
}
});
//new code below this line
let widthInput = document.getElementById('width');
widthInput.addEventListener('change', (event) => {
rect.set('width', parseInt(widthInput.value));
canvas.renderAll();
});
let heightInput = document.getElementById('height');
heightInput.addEventListener('change', (event) =>
rect.set('height', parseInt(heightInput.value));
canvas.renderAll();
});