问题
I've seen this post and tried to do my own function using only the X scaling.
fabric.Object.prototype.transform = function (ctx){
var m;
if (this.group && !this.group._transformDone) {
m = this.calcTransformMatrix();
ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
return;
}
else {
m = this.calcOwnMatrix();
//code I've wrote
if (this.my && this.my.ignoreZoom != undefined && this.my.ignoreZoom){
var scaleX = 1.0 / this.canvas.viewportTransform[0];
ctx.transform(scaleX, 0, 0, 1, m[4] - 0.5, 0);
ctx.transform(m[0], m[1], m[2], m[3], 1, m[5]);
}
//end of custom code
else{
ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
}
}
}
only problem is that the object transformation is from center. Which means if I have a square of 10 * 10 pixels
with left = 0
and top = 0
and zoom, I'll have no problem on zoom = 1
but when I increase zoom let's say by 2. my object still starts at 0 but my object appears at the middle of my 20 * 10
selection.
fabric.Object.prototype.transform = function (ctx){
var m;
if (this.group && !this.group._transformDone) {
m = this.calcTransformMatrix();
ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
return;
}
else {
m = this.calcOwnMatrix();
if (this.ignoreZoom){
var zoomX = 1.0 / this.canvas.viewportTransform[0];
ctx.transform(zoomX, 0, 0, 1, m[4] - 0.5, 0);
ctx.transform(m[0], m[1], m[2], m[3], 1, m[5]);
}
else if (this.ignoreZoomHLine){
var zoomX = 1.0 / this.canvas.viewportTransform[0];
ctx.transform(zoomX, 0, 0, 1, m[4], 0);
ctx.transform(m[0], m[1], m[2], m[3], 1, m[5]);
}
else{
ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
}
}
}
var canvas = new fabric.Canvas('c') ;
var line1 = new fabric.Line([0, 5, 20, 15],{
strokeWidth: 1,
stroke: 'black',
ignoreZoomHLine: true
});
var line2 = new fabric.Line([0, 0, 0, 50],{
strokeWidth: 1,
stroke: 'black',
ignoreZoom: true
});
canvas.add(line1, line2) ;
$('#zoomIn').click(function(){
var vpt = canvas.viewportTransform;
var scaleX = vpt[0] + 1;
canvas.setViewportTransform([scaleX, 0, 0, 1, 0, 0]);
}) ;
$('#zoomOut').click(function(){
var vpt = canvas.viewportTransform;
var scaleX = (vpt[0] - 1) < 1 ? 1 : vpt[0] - 1;
canvas.setViewportTransform([scaleX, 0, 0, 1, 0, 0]) ;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.3.2/fabric.min.js" integrity="sha256-tzYSKRkV1Ga9YrVBiNHG44eEQyRcwtNrqOMh2+CTlec=" crossorigin="anonymous"></script>
<button id="zoomIn">+</button>
<button id="zoomOut">-</button>
<div id="canvasContainer">
<canvas id="c" width="400" height="400"></canvas>
</div>
this snippet speaks for itself. At the beginning all lines are joined together. but after transform the object is separated.
Any help is greatly appreciated
来源:https://stackoverflow.com/questions/57600148/keeping-same-object-size-while-zooming-with-same-left-origin-in-fabricjs