您選擇將圖像顯示爲縮放的方式非常繁重。 有更快的方式,不需要所有這些圖紙。
您的解決方案涉及在新畫布上創建一個模式。與緩存
畫布 模式創造 平局矩形 畫布創作 平局圖像這是一個簡單的解決方案,不涉及圖案或緩存。
它包括在重寫fabric.Image渲染的方法來表現不同使用自定義個zoomLevel財產和ctx.drawImage(的完整簽名)
fabric.Image.prototype._render = function(ctx) {
var fwidth = this._element.width/(this.zoomLevel + 1);
var fheight = this._element.height/(this.zoomLevel + 1);
var wdiff = (fwidth - this._element.width)/2;
var hdiff = (fheight - this._element.height)/2;
ctx.drawImage(this._element, -wdiff, -hdiff, fwidth, fheight, -this.width/2, - this.height/2, this.width, this.height);
}
var canvas = this.__canvas = new fabric.Canvas('c');
fabric.Image.fromURL("https://images2.alphacoders.com/147/147320.png", function(img) {
var zoomLevel = 0;
var zoomLevelMin = 0;
var zoomLevelMax = 3;
img.zoomLevel = 0
img.scale(0.1);
canvas.add(img);
img.zoomIn = function() {
if (zoomLevel < zoomLevelMax) {
zoomLevel += 0.1;
img.zoomLevel = zoomLevel;
}
};
img.zoomOut = function() {
zoomLevel -= 0.1;
if (zoomLevel < 0) zoomLevel = 0;
if (zoomLevel >= zoomLevelMin) {
img.zoomLevel = zoomLevel;
}
};
});
canvas.on('mouse:wheel', function(option) {
var imgObj = canvas.getActiveObject();
if (!imgObj) return;
option.e.preventDefault();
if (option.e.deltaY > 0) {
imgObj.zoomOut();
} else {
imgObj.zoomIn();
}
canvas.renderAll();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.17/fabric.js"></script>
<h1> FabricJS imageHelper</h1>
<div id="canvasContainer">
<canvas id="c" width="1920" height="600"></canvas>
</div>
<br>
它沒有解決我的問題。但它比我的實現更簡單,更快捷。太好了!非常感謝@AndreaBogazzi。 – Jacky
所以我可能沒有得到你的問題。你能解釋得更好嗎? – AndreaBogazzi