我可以更新HTML上显示的rect的宽度和高度吗? 因为rect可以缩放宽度和高度所以我希望它也可以更新,但我不知道如何。有什么办法吗?
<html>
<canvas id="c" width="900" height="720"></canvas>
<p id="show"></p>
<button onclick="addRect2()">Rect</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.19/fabric.js"></script>
</html>
JS
var width;
var height;
var canvas = new fabric.Canvas('c');
window.addRect2 = function(width,height){
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'black',
width: 250,
height: 250,
});
canvas.add(rect);
width = rect.width;
height = rect.height;
document.getElementById("show").innerHTML = "Width and Height" + width " " + height;}
答案 0 :(得分:1)
尝试使用这些JS代码。确保将fabric.js库导入您的html代码。
var width;
var height;
window.addRect2 = function(width,height){
var canvas = new fabric.Canvas('c');
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'black',
width: 250,
height: 250,
});
canvas.add(rect);
width = rect.width;
height = rect.height;
document.getElementById("show").innerHTML = "Width and Height" + width + " " + height;}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.19/fabric.js"></script>
<canvas id="c" width="900" height="720"></canvas>
<p id="show"></p>
<button onclick="addRect2()">Rect</button>
&#13;
答案 1 :(得分:1)
var width,height;
var canvas = new fabric.Canvas('c');
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'black',
width: 250,
height: 250,
});
canvas.add(rect);
var el = document.getElementById("show");
displayDim();
rect.on('modified',function(){
displayDim();
})
rect.on('scaling',function(){
displayDim();
})
function displayDim(){
width = parseInt(rect.width * rect.scaleX);
height = parseInt(rect.height * rect.scaleY);
el.innerHTML = "Width: " + width + "px and Height: " + height+"px";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.19/fabric.js"></script>
<canvas id="c" width="500" height="400"></canvas>
<p id="show"></p>
使用events,而scaling
/ modified
更新宽度/高度。要在缩放后获得高度/宽度,您需要分别与scaleY / scaleX相乘。