fabric.js
I’ve encountered a problem where, after I zoom into the canvas using the cursor focus point (as shown by the blue dot in the first image), and then move the cursor to another position to zoom out (as shown by the black dot in the second image), I cannot restore it to its original state (i.e., how it appeared before any zooming) because the red square is no longer in the center of the canvas. How can I ensure that when zooming out to zoom=1, it returns to the same state as before any zooming?
<script src="https://unpkg.com/[email protected]/dist/fabric.min.js"></script>
<style>
canvas {
border: 1px solid #ccc;
}
</style>
</head>
<body>
<canvas id="c"> </canvas>
<script>
var canvas = new fabric.Canvas('c',{ width: 400, height: 400 });
var rect = new fabric.Rect({
originX:"center",
originY:"center",
left:200,
top:200,
stroke: "red",
strokeWidth: 1,
fill:"red",
width: 100,
height: 100,
hasControls:false
});
canvas.add(rect);
function onMouseWheel(options) {
var delta = options.e.deltaY;
var zoom = canvas.getZoom();
if (delta < 0) {
zoom =zoom+0.1;
if (zoom > 20) {
zoom = 20;
}
canvas.zoomToPoint({
x: options.e.offsetX,
y: options.e.offsetY},
zoom);
} else {
zoom =zoom-0.1
if (zoom < 1) {
zoom = 1;
}
canvas.zoomToPoint({ x:200,y:200}, zoom);
}
options.e.preventDefault();
options.e.stopPropagation();
canvas.renderAll();
}
canvas.on('mouse:wheel', onMouseWheel);
</script>
</body>
</html>
olivia is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.