I am looking for to solve one final issue in this. If you zoom in at one point and then zoom out at some other point on the canvas the image doesn't come back to the original position(centre of the canvas). Also set the maximum zoom out to 1. If anyone have solution for my problem then solve it, its very urget.
This is my code:
const canvas = new fabric.Canvas("canvas",{
width:700,
height:450,
backgroundColor:"grey"
// selection:false
});
canvas.on('mouse:wheel', function(opt) {
var delta = opt.e.deltaY;
// console.log(delta)
var zoom = canvas.getZoom();
// console.log(zoom)
zoom *= 0.999 ** delta;
if (zoom > 40) zoom = 40;
if (zoom < 1) zoom = 1;
canvas.zoomToPoint({ x: opt.e.offsetX, y: opt.e.offsetY }, zoom);
opt.e.preventDefault();
opt.e.stopPropagation();
});
canvas.renderAll();
//get image from user
var upload_image="";
const image = document.querySelector("#image");
image.addEventListener("change",()=>{
// console.log(image.files)
const reader = new FileReader();
// console.log(reader)
reader.addEventListener("load",()=>{
upload_image=reader.result;
})
reader.readAsDataURL(image.files[0]);
});
const setImage =() =>{
setImg();
}
const setImg = ()=>{
// canvas.backgroundImage=img;
fabric.Image.fromURL(upload_image,(img)=>{
// img.width=500;
// img.height=500;
canvas.backgroundImage=img;
img.center();
img.centerV();
img.centerH();
canvas.renderAll();
// canvas.add(img);
});
}
my html code:
<body class="center">
<div class="container center">
<H1>IMAGE zoom IN and OUT</H1>
<div id="canva">
<canvas id="canvas"></canvas>
</div>
<input type="file" accept="image/*" id="image">
<button id="btn" onclick="setImage()">Upload Image</button>
</div>
<script src="fabric.min.js"></script>
<script src="index.js"></script>
</body>