How to display a Canvas in a Bootstrap Modal - javascript

I created a map where you can book bikes via Javascript.
The user is supposed to :
1) select a bike station (green station = bikes are available)
2) click on a button (reserver button)
3) sign in a canvas (in a modal)
The page is here :
http://p4547.phpnet.org/bikes/reservation.html
In my javascript, the Class Object is called this way :
document.addEventListener("DOMContentLoaded", event => {
new Signature();
This code is working fine if the canvas is located in the body of the page.
But the code is not working if the canvas is located in the modal.
I tried to code this way :
$('#bookingmodal').on('shown.bs.modal',function(event){
new Signature();
});
My modal ID is : #bookingmodal

Your problem is in the calculation of the coordinates for the mouse-position inside the canvas. If you resize the page to a really small window the drawing sometimes works (with an ugly offset).
I took your Signature-class and replaced the calculation for the mouse-position inside the canvas with a function that calculates the correct position of the mouse and also handles possible scaling of the bitmap used by the canvas:
updateMousePosition(mX, mY) {
let rect = this.canvas.getBoundingClientRect();
let scaleX = this.canvas.width / rect.width;
let scaleY = this.canvas.height / rect.height;
this.cursorX = (mX - rect.left) * scaleX;
this.cursorY = (mY - rect.top) * scaleY;
}
Example:
class Signature {
constructor() {
this.color = "#000000";
this.sign = false;
this.begin_sign = false;
this.width_line = 5;
this.canvas = document.getElementById('canvas');
this.offsetLeft = this.canvas.offsetLeft;
this.offsetTop = this.canvas.offsetTop;
this.context = canvas.getContext('2d');
this.context.lineJoin = 'round';
this.context.lineCap = 'round';
this.whenMouseDown();
this.whenMouseUp();
this.whenMouseMove();
this.createSignature();
this.clearCanvas();
this.resetCanvas();
}
updateMousePosition(mX, mY) {
let rect = this.canvas.getBoundingClientRect();
let scaleX = this.canvas.width / rect.width;
let scaleY = this.canvas.height / rect.height;
this.cursorX = (mX - rect.left) * scaleX;
this.cursorY = (mY - rect.top) * scaleY;
}
whenMouseDown() {
document.addEventListener("mousedown", ({
pageX,
pageY
}) => {
this.sign = true;
this.updateMousePosition(pageX, pageY);
})
}
whenMouseUp() {
document.addEventListener("mouseup", () => {
this.sign = false;
this.begin_sign = false;
})
}
whenMouseMove() {
this.canvas.addEventListener('mousemove', ({
pageX,
pageY
}) => {
if (this.sign) {
this.updateMousePosition(pageX, pageY);
this.createSignature();
}
})
}
createSignature() {
if (!this.begin_sign) {
this.context.beginPath();
this.context.moveTo(this.cursorX, this.cursorY);
this.begin_sign = true;
} else {
this.context.lineTo(this.cursorX, this.cursorY);
this.context.strokeStyle = this.color;
this.context.lineWidth = this.width_line;
this.context.stroke();
}
}
clearCanvas() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
resetCanvas() {
document.getElementById("reset").addEventListener("click", () => {
this.clearCanvas();
})
}
}
document.addEventListener("DOMContentLoaded", event => {
new Signature();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<button type="button" class="btn btn-success" data-target="#bookingmodal" data-toggle="modal">Réserver</button>
<div aria-labelledby="exampleModalLongTitle" class="modal fade" id="bookingmodal" role="dialog" tabindex="-1" style="display: none;" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Réservation</h5><button aria-label="Close" class="close" data-dismiss="modal" type="button"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="guide">
<div class="row item">
<div class="col-md-12 order-md-2">
<h2 class="item-heading">Signature. <span class="text-muted">Signez pour valider votre réservation.</span></h2>
<canvas id="canvas" width="250" height="250">
</canvas>
<form>
<input type="button" id="reset" value="Réinitialiser" class="btn btn-danger">
</form>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" data-dismiss="modal" type="button">Fermer</button>
</div>
</div>
</div>
</div>

Related

Need to crop canvas and not resize it using jquery

I'm actually working on a project which overlay two image, with one that the user upload it and the second is by default.
My only problem is when the uploaded image is a rectangle and not a square, the canvas is resizing it. I need that the canvas crop my image, and be a square. Then I can apply the filter.
Here is my code:
$('.file1, .file2').on('change', function() {
var reader = new FileReader(),
imageSelector = $(this).data('image-selector');
if (this.files && this.files[0]) {
reader.onload = function(e) {
imageIsLoaded(e, imageSelector)
};
reader.readAsDataURL(this.files[0]);
}
});
$('.btn-merge').on('click', merge);
function imageIsLoaded(e, imageSelector) {
$(imageSelector).attr('src', e.target.result);
$(imageSelector).removeClass('hidden');
};
function merge() {
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
imageObj1 = new Image(),
imageObj2 = new Image();
canvas.width = 300;
canvas.height = 300;
imageObj1.src = $('.image1').attr('src');
imageObj1.onload = function() {
ctx.globalAlpha = 1;
ctx.drawImage(imageObj1, 0, 0, 300, 300);
imageObj2.src = $('.image2').attr('src');
imageObj2.onload = function() {
ctx.globalAlpha = 1;
ctx.drawImage(imageObj2, 0, 0, 300, 300);
var img = canvas.toDataURL('img/png');
$('.merged-image').attr('src', img);
var mergedimage = document.getElementById('mergedimage');
$('.merged-image').removeClass('hidden');
$("#downloadfinal").attr("href", mergedimage.src);
}
};
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div class="container-fluid shadow">
<div class="container d-flex flex-column justify-content-center">
<div class="row mb-1 ">
<h2>Votre photo ici : </h2>
<label class="custom ml-3 hover-underline-animation"> <input class="ml-2 file1" type="file" data-image-selector=".image1" />Selectionner un fichier</label>
</div>
<img class="image1 hidden mb-4" alt="abs" width="200px" height="auto" />
<div class="row">
<h2 class="mr-2 ">Filtre par défaut : </h2>
<img alt="abs image3" width="200px" height="auto" src="img/filtre.png" />
</div>
<div class="otherfilter">
<div class="row mt-5 mb-5">
<h2 class="">Mettez un autre filtre ici : </h2>
<label class="custom ml-3 hover-underline-animation"> <input class="ml-2 file2" type="file" data-image-selector=".image2" />Selectionner un fichier</label>
</div>
<img class="hidden image2" alt="ab" width="200px" height="auto" src="img/filtre.png">
</div>
</div>
<br />
<div class="text-center mb-5">
<input class="btn-merge mb-3" type="button" value="Appliquer le filtre" />
<br />
<img class="merged-image hidden mb-3" id="mergedimage" alt="merged image" />
<canvas id="canvas" class="hidden"></canvas>
<br>
<a class="btn-dl" id="downloadfinal" role="button" href="#" download="photo_profil_modifie">
<i class="mr-2 bi bi-download"></i>Télécharger
</a>
</div>
Thanks for read this, hope my english is good, if you don't understand tell me.
To do this you need to scale the input image to fit the canvas either horizontally or vertically while maintaining it's aspect ratio.
That's not hard to do as things are a bit easier since the canvas is squarish. Say we have a canvas of 300 x 300 pixel and we want to draw a non-square image of 400 x 300 onto. First we take the width or height of the canvas - it does not really matter as it's the same - and divide it by the bigger side of the image - 400 in this case.
300 / 400 == 0.75
This is the scale we need to multiply both the width and height of the image before drawing it onto the canvas.
Here's an example:
let canvas = document.getElementById('canvas');
let context = canvas.getContext('2d');
let imageObj1 = new Image();
imageObj1.crossOrigin = 'anonymous';
imageObj1.crossOrigin = 'anonymous';
imageObj1.onload = () => {
let scale = imageObj1.width > imageObj1.height ? canvas.width / imageObj1.width : canvas.height / imageObj1.height;
context.drawImage(imageObj1, canvas.width / 2 - imageObj1.width * scale / 2, canvas.height / 2 - imageObj1.height * scale / 2, imageObj1.width * scale, imageObj1.height * scale);
}
imageObj1.src = 'https://api.codetabs.com/v1/proxy?quest=https://picsum.photos/id/237/300/400';
#canvas {
background: blue;
}
<canvas id="canvas" width="300" height="300"></canvas>
If you prefer to not have unused area on your canvas and stretch the image to the whole canvas and crop the exceess, you simply divide the smaller side of your image by the canvas width/height.
For example:
//ctx.drawImage(imageObj1, 0, 0, 300, 300);let image = new Image();
let canvas = document.getElementById('canvas');
let context = canvas.getContext('2d');
let imageObj1 = new Image();
imageObj1.crossOrigin = 'anonymous';
imageObj1.crossOrigin = 'anonymous';
imageObj1.onload = () => {
let scale = imageObj1.width < imageObj1.height ? canvas.width / imageObj1.width : canvas.height / imageObj1.height;
context.drawImage(imageObj1, canvas.width / 2 - imageObj1.width * scale / 2, canvas.height / 2 - imageObj1.height * scale / 2, imageObj1.width * scale, imageObj1.height * scale);
}
imageObj1.src = 'https://api.codetabs.com/v1/proxy?quest=https://picsum.photos/id/237/300/400';
<canvas id="canvas" width="300" height="300"></canvas>

How to draw in more than two canvases HTML & JS

I'm working on a proyect and i need to draw in almost 5 canvas. I've created the first canvas successfully but when i put in the code the second i only can draw on this latest canvas.
I read than the problem can be the context("2d") i tryed to separate saving in a different ctx varaible like, ctx2 or things like this.
This is my code:
HTML
<!--First Canvas-->
<div class="col-sm-12 col-lg-6 mt-5 d-flex flex-column justify-content-center">
<div id="contenedor-pizarra-cervical" class="contenedor-pizarra mx-auto">
<canvas id="pizarra-cervical"></canvas>
</div>
</div>
<!--Second Canvas-->
<div class="col-sm-12 col-lg-6 mt-5 d-flex flex-column justify-content-center">
<div id="contenedor-pizarra-postural" class="contenedor-pizarra mx-auto">
<canvas id="pizarra-postural"></canvas>
</div>
</div>
JS OF THE FIRST CANVAS WORKING OK:
//Canvas Cervical
var canvasCervical = document.getElementById("pizarra-cervical");
var ctx = canvasCervical.getContext("2d");
var painting = document.getElementById("contenedor-pizarra-cervical");
var paintStyle = getComputedStyle(painting);
canvasCervical.width = parseInt(paintStyle.getPropertyValue("width"));
canvasCervical.height = parseInt(paintStyle.getPropertyValue("height"));
var mouse = {x: 0, y: 0};
canvasCervical.addEventListener('mousemove', function(e){
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop
}, false);
ctx.lineWidth = 3;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = '#7baeb0';
canvasCervical.addEventListener('mousedown', function(e){
ctx.beginPath();
ctx.moveTo(mouse.x, mouse.y);
canvasCervical.addEventListener('mousemove', onPaint, false);
}, false);
canvasCervical.addEventListener('mouseup', function(){
canvasCervical.removeEventListener('mousemove', onPaint, false)
},false);
var onPaint = function (){
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
};
If you require the same behaviour to happen on multiple canvasses, then you could define the configuration logic in its own function, providing the canvas element as an argument, like this:
let configureCanvas = canvas => {
let painting = canvas.parentNode;
let paintStyle = getComputedStyle(painting);
let mouse = { x: 0, y: 0 };
let onPaint = () => {
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
};
canvas.width = parseInt(paintStyle.getPropertyValue("width"));
canvas.height = parseInt(paintStyle.getPropertyValue("height"));
let ctx = canvas.getContext("2d");
ctx.lineWidth = 3;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = '#7baeb0';
canvas.addEventListener('mousemove', function(e) {
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop
}, false);
canvas.addEventListener('mousedown', function(e) {
ctx.beginPath();
ctx.moveTo(mouse.x, mouse.y);
canvas.addEventListener('mousemove', onPaint, false);
}, false);
canvas.addEventListener('mouseup', function() {
canvas.removeEventListener('mousemove', onPaint, false)
}, false);
canvas.nextElementSibling.addEventListener('click', function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
}
configureCanvas(document.getElementById("pizarra-cervical"));
configureCanvas(document.getElementById("pizarra-postural"));
canvas {
border: 1px solid #CCC;
}
<!--First Canvas-->
<div class="col-sm-12 col-lg-6 mt-5 d-flex flex-column justify-content-center">
<div id="contenedor-pizarra-cervical" class="contenedor-pizarra mx-auto">
<canvas id="pizarra-cervical"></canvas>
<button class="clear">Clear</button>
</div>
</div>
<!--Second Canvas-->
<div class="col-sm-12 col-lg-6 mt-5 d-flex flex-column justify-content-center">
<div id="contenedor-pizarra-postural" class="contenedor-pizarra mx-auto">
<canvas id="pizarra-postural"></canvas>
<button class="clear">Clear</button>
</div>
</div>
Taking this a step further, I'd suggest defining your own Class to handle the initialisation, configuration and event handlers of your canvas elements, but that's well outside the remit of this question.

Canvas in Bootstrap modal is giving me wrong mouse coordinates

Im trying to figure out what im dooing wrong. I have a hmtl5 canvas inside a bootstrap modal. The canvas is a selecting game where you select objects inside the canvas and manipulate them.
Unfortunately it works allright in the center of the 600x600px Canvas but im getting a wierd offset when im trying to get the coordinates in the corner of the picture. The offset is getting bigger as you get closer to the corners
Here's my code.
Thank you very much in advance!
Javascript:
document.addEventListener('DOMContentLoaded', (ev) => {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
canvas.width = 600;
canvas.height = 600;
let imgObj = new Image();
imgObj.onload = function() {
let w = canvas.width;
let nw = imgObj.naturalWidth; //1350
let nh = imgObj.naturalHeight; //900
console.log(nw);
console.log(nh);
let aspect = nw / nh;
let h = w / aspect;
console.log('height', h)
canvas.height = h;
soldTilesDisplay.textContent = totalTiles-soldTiles;
ctx.drawImage(imgObj, 0, 0, w, h);
rectangulize_with_IDs();
fillarraywithrandomTiles(soldTiles);
//greyscaleOriginal();
//ctx.drawImage(imgObj, dx, dy);
//ctx.drawImage(imgObj, dx, dy, dw, dh);
//ctx.drawImage(imgObj, sx, sy, sw, sh, dx, dy, dw, dh);
};
function getMousePosition(canvas, event) {
let rect = canvas.getBoundingClientRect();
let x = event.clientX - Math.floor(rect.left);
let y = event.clientY - Math.floor(rect.top);
storePixelArray(x, y); // originale "Store in Array funktion"
store_rect(x,y);
clickcounter = clickcounter + 1;
console.log("Exact Coordinates: X: " + x,
" Y: " + y, "CLick Counter: "+ clickcounter);
}
Html:
<div>
<!-- Bootstrap Modal here!-->
<div class="row">
<div class="col-lg-4">
<!-- Bootstrap Modal here!-->
<div class="modal fade" id="myModal1">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h3>WIN!</h3>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="col-md-6">
<canvas id="canvas" style="background-image: url('/images/Berge.png')"></canvas>
</div>
<div class="col-md-6 justify-content-center">
<div class="card text-center" style="width: 30rem;">
<div class="card-body">
<h5 class="card-title" id="Punktestand"> Card Title
Score:
</h5>
<p class="card-text" id="paragraphImModal">With supporting
text below as a natural
lead-in to additional content.</p>
<button type="button" class="btn btn-default" id="usePointsPixelButton">
Select Pixel first</button>
<br>
<h5 class="selectedPixelAmount" id="AmountOfPixels"> </h5>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-lg" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
I found the problem after running into the same Issue.
It is because the class .modal-dialog and every subclass under it has a relative positioning. just set the positioning to unset and you get the correct coordinates.
in my case i had to change following classes:
.modal-dialog {
position: unset;
}
.modal-content {
position: unset;
}
.modal-body {
position: unset;
}
.alert {
position: unset;
}
If you want you can do css stuff like "just change the position of modal-body inside modal dialog" so you dont mess up anything else :)

How to add Image to the canvas draw inside on the Modal Dialog

I can Draw in canvas inside normal HTML page. But my question is when i put canvas inside Modal Dialog drawing function not working.
I added my code with this.
I don't know this is happening because of view overlapping.Any though about how to fix this would be appreciated.
var canvas, ctx, flag = false,
prevX = 0,
currX = 0,
prevY = 0,
currY = 0,
dot_flag = false;
var x = "black",
y = 2;
$('#edit-question-image').on('show.bs.modal', function (e) {
var QuestionId = $(e.relatedTarget).data('question-id');
var photo = $(e.relatedTarget).data('imgsrc');
$(e.currentTarget).find('input[id="questionId"]').val(QuestionId);
$(e.currentTarget).find('img[id="canvasimg"]').attr("src", photo);
canvas = document.getElementById('can');
ctx = canvas.getContext("2d");
var img = document.getElementById("canvasimg");
ctx.drawImage(img, 10, 10);
w = canvas.width;
h = canvas.height;
canvas.addEventListener("mousemove", function (e) {
findxy('move', e)
}, false);
canvas.addEventListener("mousedown", function (e) {
findxy('down', e)
}, false);
canvas.addEventListener("mouseup", function (e) {
findxy('up', e)
}, false);
canvas.addEventListener("mouseout", function (e) {
findxy('out', e)
}, false);
});
function color(obj) {
console.log("colour", obj.id)
switch (obj.id) {
case "red":
x = "red";
case "black":
x = "black";
break;
case "white":
x = "white";
break;
}
y==2
}
function draw() {
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(currX, currY);
ctx.strokeStyle = x;
ctx.lineWidth = y;
ctx.stroke();
ctx.closePath();
}
function erase() {
var m = confirm("Want to clear");
if (m) {
ctx.clearRect(0, 0, w, h);
document.getElementById("canvasimg").style.display = "none";
}
}
function save() {
document.getElementById("canvasimg").style.border = "2px solid";
var dataURL = canvas.toDataURL();
document.getElementById("canvasimg").src = dataURL;
document.getElementById("canvasimg").style.display = "inline";
}
function findxy(res, e) {
if (res == 'down') {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
flag = true;
dot_flag = true;
if (dot_flag) {
ctx.beginPath();
ctx.fillStyle = x;
ctx.fillRect(currX, currY, 2, 2);
ctx.closePath();
dot_flag = false;
}
}
if (res == 'up' || res == "out") {
flag = false;
}
if (res == 'move') {
if (flag) {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
draw();
}
}
}
HTML Code
<div id="edit-question-image" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content" style="padding: 16px;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 id="editPhoto-Title" class="sc-badge sc-safe" style="padding: 4px 3px !important;">Modify Photo</h4>
</div>
<div class="modal-body">
<div id="editPhoto-ImgContainer_Q">
<canvas id="can" width="400" height="400" style="top:10%;left:10%;border:2px solid;"></canvas>
<div style="top:12%;left:43%;">Choose Color</div>
<div style="top:15%;left:47%;width:10px;height:10px;background:red;" id="red" onclick="color(this)"></div>
<div style="top:17%;left:47%;width:10px;height:10px;background:black;" id="black" onclick="color(this)"></div>
<div style="top:20%;left:43%;">Eraser</div>
<div style="top:22%;left:45%;width:15px;height:15px;background:white;border:2px solid;" id="white" onclick="color(this)"></div>
<img id="canvasimg" style="position:absolute;top:10%;left:52%; display:none;" >
<input type="button" value="save" id="btn" size="30" onclick="save()" style="top:55%;left:10%;">
<input type="button" value="clear" id="clr" size="23" onclick="erase()" style="top:55%;left:15%;">
</div>
<div class="modal-footer">
<input type="button" id="btnCloseDialogEditPhoto" class="modal-button" style="margin: 8px;" value="Cancel" data-dismiss="modal" />
<input type="submit" id="btnSaveEditPhoto_Q" class="modal-button" style="margin: 8px; float: right;" value="Submit" data-dismiss="modal" />
</div>
</div>
</div>

zoom in zoom out image on scrolling in javascript

I created tabs with image.When I scroll on the image it will zoom in and zoom out. But I am facing the problem,in only first tab it is working with function zoom in & zoom out(when i scroll).I didn't get what i'm doing wrong.
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>zoom</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<style type="text/css">
ul li{
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Panel title</h3>
<span class="pull-right">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class="active">Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
<li>Tab 4</li>
</ul>
</span>
</div>
<div class="panel-body">
<br />
<br />
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<div class="container">
<div class="slide">
<img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab2">
<div class="container">
<div class="slide">
<img class='zoom' src='abc.jpg' alt='abc' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab3">
<div class="container">
<div class="slide">
<img class='zoom' src='xy.jpg' alt='xy' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab4">
<div class="container">
<div class="slide">
<img class='zoom' src='rec.png' alt='rec' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- <img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/>
<br />
<img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/> -->
<script src="wheelzoom.js"></script>
<script>
wheelzoom(document.querySelector('img.zoom'));
</script>
</body>
</html>
wheelzoom.js
window.wheelzoom = (function(){
var defaults = {
zoom: 0.10,
maxZoom: false,
initialZoom: 1,
};
var main = function(img, options){
if (!img || !img.nodeName || img.nodeName !== 'IMG') { return; }
var settings = {};
var width;
var height;
var bgWidth;
var bgHeight;
var bgPosX;
var bgPosY;
var previousEvent;
var cachedDataUrl;
function setSrcToBackground(img) {
img.style.backgroundRepeat = 'no-repeat';
img.style.backgroundImage = 'url("'+img.src+'")';
cachedDataUrl = 'data:image/svg+xml;base64,'+window.btoa('<svg xmlns="http://www.w3.org/2000/svg" width="'+img.naturalWidth+'" height="'+img.naturalHeight+'"></svg>');
img.src = cachedDataUrl;
}
function updateBgStyle() {
if (bgPosX > 0) {
bgPosX = 0;
} else if (bgPosX < width - bgWidth) {
bgPosX = width - bgWidth;
}
if (bgPosY > 0) {
bgPosY = 0;
} else if (bgPosY < height - bgHeight) {
bgPosY = height - bgHeight;
}
img.style.backgroundSize = bgWidth+'px '+bgHeight+'px';
img.style.backgroundPosition = bgPosX+'px '+bgPosY+'px';
}
function reset() {
bgWidth = width;
bgHeight = height;
bgPosX = bgPosY = 0;
updateBgStyle();
}
function onwheel(e) {
var deltaY = 0;
e.preventDefault();
if (e.deltaY) { // FireFox 17+ (IE9+, Chrome 31+?)
deltaY = e.deltaY;
} else if (e.wheelDelta) {
deltaY = -e.wheelDelta;
}
// As far as I know, there is no good cross-browser way to get the cursor position relative to the event target.
// We have to calculate the target element's position relative to the document, and subtrack that from the
// cursor's position relative to the document.
var rect = img.getBoundingClientRect();
var offsetX = e.pageX - rect.left - window.pageXOffset;
var offsetY = e.pageY - rect.top - window.pageYOffset;
// Record the offset between the bg edge and cursor:
var bgCursorX = offsetX - bgPosX;
var bgCursorY = offsetY - bgPosY;
// Use the previous offset to get the percent offset between the bg edge and cursor:
var bgRatioX = bgCursorX/bgWidth;
var bgRatioY = bgCursorY/bgHeight;
// Update the bg size:
if (deltaY < 0) {
bgWidth += bgWidth*settings.zoom;
bgHeight += bgHeight*settings.zoom;
} else {
bgWidth -= bgWidth*settings.zoom;
bgHeight -= bgHeight*settings.zoom;
}
if (settings.maxZoom) {
bgWidth = Math.min(width*settings.maxZoom, bgWidth);
bgHeight = Math.min(height*settings.maxZoom, bgHeight);
}
// Take the percent offset and apply it to the new size:
bgPosX = offsetX - (bgWidth * bgRatioX);
bgPosY = offsetY - (bgHeight * bgRatioY);
// Prevent zooming out beyond the starting size
if (bgWidth <= width || bgHeight <= height) {
reset();
} else {
updateBgStyle();
}
}
function drag(e) {
e.preventDefault();
bgPosX += (e.pageX - previousEvent.pageX);
bgPosY += (e.pageY - previousEvent.pageY);
previousEvent = e;
updateBgStyle();
}
function removeDrag() {
document.removeEventListener('mouseup', removeDrag);
document.removeEventListener('mousemove', drag);
}
// Make the background draggable
function draggable(e) {
e.preventDefault();
previousEvent = e;
document.addEventListener('mousemove', drag);
document.addEventListener('mouseup', removeDrag);
}
function load() {
var initial = Math.max(settings.initialZoom, 1);
if (img.src === cachedDataUrl) return;
var computedStyle = window.getComputedStyle(img, null);
width = parseInt(computedStyle.width, 10);
height = parseInt(computedStyle.height, 10);
bgWidth = width * initial;
bgHeight = height * initial;
bgPosX = -(bgWidth - width)/2;
bgPosY = -(bgHeight - height)/2;;
setSrcToBackground(img);
img.style.backgroundSize = bgWidth+'px '+bgHeight+'px';
img.style.backgroundPosition = bgPosX+'px '+bgPosY+'px';
img.addEventListener('wheelzoom.reset', reset);
img.addEventListener('wheel', onwheel);
img.addEventListener('mousedown', draggable);
}
var destroy = function (originalProperties) {
img.removeEventListener('wheelzoom.destroy', destroy);
img.removeEventListener('wheelzoom.reset', reset);
img.removeEventListener('load', load);
img.removeEventListener('mouseup', removeDrag);
img.removeEventListener('mousemove', drag);
img.removeEventListener('mousedown', draggable);
img.removeEventListener('wheel', onwheel);
img.style.backgroundImage = originalProperties.backgroundImage;
img.style.backgroundRepeat = originalProperties.backgroundRepeat;
img.src = originalProperties.src;
}.bind(null, {
backgroundImage: img.style.backgroundImage,
backgroundRepeat: img.style.backgroundRepeat,
src: img.src
});
img.addEventListener('wheelzoom.destroy', destroy);
options = options || {};
Object.keys(defaults).forEach(function(key){
settings[key] = options[key] !== undefined ? options[key] : defaults[key];
});
if (img.complete) {
load();
}
img.addEventListener('load', load);
};
// Do nothing in IE9 or below
if (typeof window.btoa !== 'function') {
return function(elements) {
return elements;
};
} else {
return function(elements, options) {
if (elements && elements.length) {
Array.prototype.forEach.call(elements, main, options);
} else if (elements && elements.nodeName) {
main(elements, options);
}
return elements;
};
}
}());
When i scroll it is zoom in and zoom out but only in first tab.What I did wrong,i can't understand.Please help me.Thank you.
Nice work i worked it out and find that you are using wheelzoom(document.querySelector('img.zoom')); here in this code you are using querySelector where this code will return only one element not all element instead of this code you need to use wheelzoom(document.querySelectorAll('img.zoom')); then your example will work . I have tried and its working

Categories

Resources