我正在使用一個函數來縮放整個fabric.js畫布,此函數以百分比形式提供值,如zoomCanvas(2.2);其中2.2意味着220%,而不是百分比我需要按比例縮放畫布以適應容器中的畫布,例如,當畫布從json數據加載到頁面上時,其初始大小爲1200px x 700px,容器大小爲500px。現在我需要找到一種方法,可以將500px轉換爲百分比值,以便整個canvas及其所有對象都適合500px。縮放面料js畫布及其所有對象
這是縮放功能,其中的因素是百分比值
function zoomCanvas(factor) {
canvas.setHeight(canvas.getHeight() * factor);
canvas.setWidth(canvas.getWidth() * factor);
if (canvas.backgroundImage) {
// Need to scale background images as well
var bi = canvas.backgroundImage;
bi.width = bi.width * factor; bi.height = bi.height * factor;
}
var objects = canvas.getObjects();
var tcounter = 0;
for (var i in objects) {
tcounter++;
//alert(tcounter);
var scaleX = objects[i].scaleX;
var scaleY = objects[i].scaleY;
var left = objects[i].left;
var top = objects[i].top;
var tempScaleX = scaleX * factor;
var tempScaleY = scaleY * factor;
var tempLeft = left * factor;
var tempTop = top * factor;
objects[i].scaleX = tempScaleX;
objects[i].scaleY = tempScaleY;
objects[i].left = tempLeft;
objects[i].top = tempTop;
objects[i].setCoords();
}
canvas.renderAll();
canvas.calcOffset();
}
你需要嗎從1200x700像素轉換爲500x500像素? – Observer
感謝您的回覆...沒有它只是一個示例容器大小將在不同的設備上不同 –