html2canvas won't take scrollHeight into account after resizing div - javascript

I am trying to usehtml2canvas to export some divs in .png format. My div has a greater height than my body which is not a problem because I can use the windowHeight option with myDiv.scrollHeight and it works perfectly.
function exp(e) {
html2canvas(e, {
windowWidth: e.scrollWidth,
windowHeight: e.scrollHeight * 1.12
}).then((canvas) => {
let a = document.createElement("a");
a.download = 'capture_' + date + '.png';
a.href = canvas.toDataURL("image/png");
a.click();
});
}
Now, the thing is, the div I'm "screening" is resizable. It shouldn't be a problem given I use the scrollHeight value but it takes the actual height into account instead of scrollHeight.
Working
Not working
I tried pretty much everything I could find on the internet, every configuration option on html2canvas, myDiv.scrollTo(0,0) as explain in this second answer
I don't know if it can help but here is my resize code :
function resize_height(e) {
topTab.scrollTop = 0
topTab.style.overflow = 'hidden'
const dx = m_pos_height - e.y;
m_pos_height = e.y;
topTab.style.height = (topTab.offsetHeight - dx) + "px"
botTab.style.height = cont - (topTab.offsetHeight - dx) + "px"
topTab.style.maxHeight = cont + 'px'
}
botTab.addEventListener("mousedown", function (e) {
if (e.offsetY < BORDER_SIZE_HEIGHT) {
m_pos_height = e.y;
document.addEventListener("mousemove", resize_height, false);
}
}, false);
document.addEventListener("mouseup", function () {
document.removeEventListener("mousemove", resize_height, false);
topTab.style.overflow = 'auto'
}, false);
topTab being the div I try to screen.

Related

Keeping iframe/image ratio when resizing on height

I managed to keep the iframe's ratio for when the user resizes the window on width, but I have trouble adding the logic for when the user resizes the window on height due to conflicting logic, since the resize on width already alters the height of the iframe.
This is the function that gets called when resizing:
function calculateAspectRatioFit(width, height, ratio) {
if(height) {
let width = ((length)/(Math.sqrt((1)/(Math.pow(ratio, 2)+1))));
return Math.round(width);
} else if(width) {
let height = ((width)/(Math.sqrt((Math.pow(ratio, 2)+1))));
return Math.round(height);
}
}
But I believe that the problem lies in the trigger:
const resizeHandler = (e) => {
console.log("inside ", parseInt(iframeHeight), iframeElement.offsetHeight);
if(parseInt(iframeWidth) > iframeElement.offsetWidth) {
// overwrite inline styling
iframeElement.style.cssText = 'height: ' + calculateAspectRatioFit(iframeElement.offsetWidth, null, iframeRatio) + 'px!important';
} else if (parseInt(iframeHeight) > window.innerHeight) {
iframeElement.style.cssText = 'width: ' + calculateAspectRatioFit(null, iframeElement.offsetHeight, iframeRatio) + 'px!important';
}
}
Got any solutions for this? (pen below)
https://codepen.io/Dragosb/pen/WNoeXRa?editors=0011
Solved, as per the codepen (link is the same as the one in the original post):
Added a container for the iframe (if you are using a modal, that can be the container):
const resizeHandler = (e) => {
// get container measures
let computedContainerStyling = getComputedStyle(iframeContainer);
let containerWidth = parseInt(computedContainerStyling.width);
let containerHeight = parseInt(computedContainerStyling.height);
if ( (containerWidth / iframeRatio) > containerHeight){
iframeHeight = containerHeight;
iframeWidth = containerHeight * iframeRatio;
} else {
iframeWidth = containerWidth;
iframeHeight = containerWidth / iframeRatio;
}
iframeElement.style.width = Math.floor(iframeWidth) + 'px';
iframeElement.style.height = Math.floor(iframeHeight) + 'px';
}
window.addEventListener('resize', resizeHandler, false);
https://codepen.io/Dragosb/pen/WNoeXRa?editors=0011

Remove function on browser width

I'm still very new to javascript and I'm learning as I build. This may be a simple fix but how would I disable a function on my parallax images ( or disable a specific js function in general ) on a smaller width?
Here's what I have so far that doesn't quite work but shows "undefined". I've been searching for a solution for a couple of days now with no luck. Any help would be appreciated.
var paraLlaxS = document.querySelector("#firstImgc2");
var paraLlaxS = document.querySelector("#secondImgc2");
var paraLlaxS = document.querySelector("#backbox1");
function setTranslate(xPos, yPos, el) {
el.style.transform = "translate3d(" + xPos + ", " + yPos + "px, 0)";
}
window.addEventListener("DOMContentLoaded", scrollLoop, false);
var xScrollPosition;
var yScrollPosition;
function scrollLoop() {
xScrollPosition = window.scrollX;
yScrollPosition = window.scrollY;
setTranslate(0, yScrollPosition * -0.2, firstImgc2);
setTranslate(0, yScrollPosition * 0.15, secondImgc2);
setTranslate(0, yScrollPosition * -0.6, backbox1);
requestAnimationFrame(scrollLoop);
if(window.innerWidth < 900) {
document.querySelector('#firstImgc2').innerHTML = window.removeEventListener("DOMContentLoaded", scrollLoop, false);
return;
} else {
}
}
You could add a conditional return at the beginning of you function. But if the width increases again you would need to listen for that to start the loop again.
function scrollLoop() {
if(window.innerWidth < 900)return;
...
I borrowed a solution from another post.
Listen for browser width for responsive web design?
This code is compatible with a wider variety of browsers as getting the screen size can vary depending on the browser.
var width = 0;
function getWindowSize() {
if (document.body && document.body.offsetWidth) {
width = document.body.offsetWidth;
}
if (document.compatMode=='CSS1Compat' &&
document.documentElement &&
document.documentElement.offsetWidth ) {
width = document.documentElement.offsetWidth;
}
if (window.innerWidth) {
width = window.innerWidth;
}
return(width);
}

Setting position to relative dynamically through Javascript

i am trying to create wave effect like Google but i am unable to set target's element position to 'relative' dynamically so that i can use 'waves-effect' class on any element.
Here is my code
let __ = (arg) => document.querySelectorAll(arg),
_ = (arg) => document.querySelector(arg);
Array.prototype.forEach.call( __(".waves-effect"), (elem) => {
elem.addEventListener('mousedown', makeWave);
elem.addEventListener('touchstart', makeWave);
});
function makeWave(event) {
let wave = document.createElement("div");
this.appendChild(wave);
// Here i want to set position to relative
// i have tried 'this.style.position = 'relative'' but it ain't working
wave.classList.add("c-ripple");
wave.setAttribute('id','i-ripple-effect');
let max = Math.max( this.clientWidth, this.clientHeight );
wave.style.height = wave.style.width = max + "px";
wave.style.left = event.clientX - this.offsetLeft - max / 2 + "px";
wave.style.top = event.clientY - this.offsetTop - max / 2 + "px";
wave.addEventListener("animationend", destroyRipple, false);
wave.addEventListener("webkitAnimationEnd", destroyRipple, false);
wave.addEventListener("oAnimationEnd", destroyRipple, false);
wave.addEventListener("MSAnimationEnd", destroyRipple, false);
}
function destroyRipple() {
_("#i-ripple-effect").remove();
}
I did search about this question, if this is answered already please correct me.
Thank YOU :)

trigger animation at the end of debounced requestanimationframe

I followed Paul Lewis's guide to debounce and requestAnimationFrame. I'm translating an image across the screen on scroll when it comes into view.
var bicycles = $('.tandem-bike', context),
lastScrollY = 0,
ticking = false;
function update() {
var windowHeight = window.innerHeight,
windowWidth = $(window).width(),
bikeTop = [];
bicycles.each( function (i, el) {
bikeTop[i] = $(this).offset();
});
bicycles.each(function(i, el) {
var position = bikeTop[i];
var fromTop = position.top - windowHeight;
var imgHeight = $(this).height();
// When this image scrolls into view.
if (lastScrollY > fromTop && lastScrollY < position.top + imgHeight && i == 1 ) { // 375 ~= height of image
var translate = Math.floor((lastScrollY - fromTop) / ((windowHeight + imgHeight + 300) / windowWidth));
console.log('add tp tranlate ', translate);
$(this).css('transform', 'translateX(' + (translate - 275) + 'px)');
}
});
ticking = false;
}
function onScroll() {
lastScrollY = window.scrollY;
requestTick();
}
function requestTick() {
if(!ticking) {
requestAnimationFrame(update);
ticking = true;
}
}
window.addEventListener('scroll', onScroll, false);
This works great and the bicycle-built-for-two slides effortlessly across the screen. However, I want the image to "bounce" when the user stops scrolling. I figure an easy way would be to add a class when the animation ends, and pull it off when the animation starts. The obvious place to do that is within the if block in requestTick().
if(!ticking) {
$('.tandem-bike').removeClass('bounce');
requestAnimationFrame(update);
$('.tandem-bike').addClass('bounce');
ticking = true;
}
or
if(!ticking) {
requestAnimationFrame(update);
$('.tandem-bike').addClass('bounce');
ticking = true;
} else {
$('.tandem-bike').removeClass('bounce');
}
}
Neither works, and I don't love then because I'm whole-sale adding classes to all the animated images on the page. (I would live with that if it worked)

HTML5 and Javascript to play videos only when visible

I am interested in setting up an HTML page with multiple video clips such that each video clip plays only while visible and then pauses when out of view.
I have found this great example of how this can be implemented with one clip, but I have been unable to modify the code to work with multiple clips. Perhaps I need to convert this code into a function for easy re-usability?
Here is what I have so far (JS Bin linked above modified for 2 clips instead of one).
This code seems to work for only one of the two clips.
<!DOCTYPE html>
<html>
<!-- Created using jsbin.com Source can be edited via http://jsbin.com/ocupor/1/edit
-->
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<style>
#right {
position: absolute;
top: 2000px;
}
#video1 {
position: absolute;
left: 2000px;
top: 2000px;
}
#video2 {
position: absolute;
left: 2000px;
top: 3000px;
}
</style>
<style id="jsbin-css">
</style>
</head>
#
<body style="width: 4000px; height: 4000px;">
<div id="info"></div>
<div id="down">
scroll down please...
</div>
<div id="right">
scroll right please...
</div>
<video id="video1">
<source src="http://video-js.zencoder.com/oceans-clip.mp4"/>
</video>
<script>
var video = document.getElementById('video1'), fraction = 0.8;
function checkScroll() {
var x = video.offsetLeft, y = video.offsetTop, w = video.offsetWidth, h = video.offsetHeight, r = x + w, //right
b = y + h, //bottom
visibleX, visibleY, visible;
visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));
visible = visibleX * visibleY / (w * h);
if (visible > fraction) {
video.play();
} else {
video.pause();
}
}
checkScroll();
window.addEventListener('scroll', checkScroll, false);
window.addEventListener('resize', checkScroll, false);
</script>
<video id="video2">
<source src="http://video-js.zencoder.com/oceans-clip.mp4"/>
</video>
<script>
var video = document.getElementById('video2'), fraction = 0.8;
function checkScroll() {
var x = video.offsetLeft, y = video.offsetTop, w = video.offsetWidth, h = video.offsetHeight, r = x + w, //right
b = y + h, //bottom
visibleX, visibleY, visible;
visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));
visible = visibleX * visibleY / (w * h);
if (visible > fraction) {
video.play();
} else {
video.pause();
}
} checkScroll();
window.addEventListener('scroll', checkScroll, false);
window.addEventListener('resize', checkScroll, false);
</script>
</body>
</html>
Using the isInViewport plugin and jQuery, here's my code for the task
$('video').each(function(){
if ($(this).is(":in-viewport")) {
$(this)[0].play();
} else {
$(this)[0].pause();
}
})
OK, I think, it must be something like this:
var videos = document.getElementsByTagName("video");
function checkScroll() {
var fraction = 0.8; // Play when 80% of the player is visible.
for(var i = 0; i < videos.length; i++) {
var video = videos[i];
var x = video.offsetLeft, y = video.offsetTop, w = video.offsetWidth, h = video.offsetHeight, r = x + w, //right
b = y + h, //bottom
visibleX, visibleY, visible;
visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));
visible = visibleX * visibleY / (w * h);
if (visible > fraction) {
video.play();
} else {
video.pause();
}
}
}
window.addEventListener('scroll', checkScroll, false);
window.addEventListener('resize', checkScroll, false);
None of the above seemed to work for me, but I finally found a way: you'll need the visible plugin, and this little piece of code right here:
$(window).scroll(function() {
$('video').each(function() {
if ($(this).visible(true)) {
$(this)[0].play();
} else {
$(this)[0].pause();
}
})
});
This will allow any video to play only when it gets into viewport. By replacing visible( true ) by visible()
, you can set it to play only when the entire video DOM element is in viewport.
Y'all need to get with the times and use IntersectionObserver (and the appropriate polyfill or babeifyl). This script will play/pause all videos on a page when they scroll in/out of view. Boom.
<script crossorigin="anonymous" src="https://polyfill.io/v3/polyfill.min.js?features=IntersectionObserver%2CIntersectionObserverEntry"></script>
<script>
let video = document.querySelector('video');
let isPaused = false;
let observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if(entry.intersectionRatio!=1 && !video.paused){
video.pause();
isPaused = true;
}
else if(isPaused) {
video.play();
isPaused=false}
});
}, {threshold: 1});
observer.observe(video);
</script>
source
Need to check if the video is visible during the scrolling.
$(window).scroll(function() {
$('video').each(function(){
if ($(this).is(":in-viewport")) {
$(this)[0].play();
} else {
$(this)[0].pause();
}
})
});
Using jQuery, isInViewport, and Coffeescript, the complete solution for me looked like this:
$(window).scroll ->
$('video:in-viewport').each -> $(#)[0].play()
$('video:not(:in-viewport)').each -> $(#)[0].pause()
Old question, but just wanted to add my two cents, I initially started with the jQuery code above, but ran into some issues with the implementation. This solution should work with multiple videos, and also prevents a problem where the user pauses a video and tries to scroll away and it just starts again:
<script>
var videoList = [];
var scrollPauseList = [];
var clickedPauseList = [];
</script>
<script>
var myScrollFunc = function() {
$(".video-js").each(function(){
var inView = $(this).is(":in-viewport");
var isPaused = $(this)[0].player.paused();
var playerIdx = videoList.indexOf(this.id);
var scrollPaused = scrollPauseList[playerIdx];
var clickPaused = clickedPauseList[playerIdx];
if (inView) {
var hasEnded = $(this)[0].player.ended();
var curTime = $(this)[0].player.currentTime();
var hasStarted = curTime > 0;
if(hasStarted && !hasEnded && !clickPaused)
{
scrollPauseList[playerIdx] = false;
$(this)[0].player.play();
}
} else if(!isPaused) {
scrollPauseList[playerIdx] = true;
$(this)[0].player.pause();
}
});
};
$(window).scroll(myScrollFunc);
</script>
<video
class="video-js" controls></video>
<script>
$(".video-js").each(function(){
videoList[videoList.length] = this.id;
scrollPauseList[scrollPauseList.length] = false;
clickedPauseList[scrollPauseList.length] = false;
});
for(var i = 0; i < videoList.length; i++)
{
var playerID = videoList[i];
var player = videojs(playerID);
player.on('pause', function() {
var pID = videoList.indexOf(this.id());
if(!scrollPauseList[pID])
{
clickedPauseList[pID] = true;
scrollPauseList[pID] = false;
}
else
{
clickedPauseList[pID] = false;
scrollPauseList[pID] = false;
}
});
}
</script>
I've scrubbed some stuff, and i'm using video-js, so you may need to modify it a bit to get your implementation to work.
Tried many solutions, the only one partially working is the one posted below. The problem is that having 3 videos on the page, the second one and the third one are basically controlled by the first one.
So they start playing when the page is loaded (while they are supposed to play when in viewport) and they get paused when the first get paused, any suggestion on having this working with multiple videos?
Tried using getElementById but didn't work, tried also jquery plugins but no good results.
Here you have the www page where you can see what happen and all source code of course.
http://185.197.128.183/~monompro/
window.onload = function() {
var videos = document.getElementsByTagName("video"),
fraction = 0.8;
function checkScroll() {
for (var i = 0; i < videos.length; i++) {
var video = videos[i];
var x = video.offsetLeft,
y = video.offsetTop,
w = video.offsetWidth,
h = video.offsetHeight,
r = x + w, //right
b = y + h, //bottom
visibleX, visibleY, visible;
visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));
visible = visibleX * visibleY / (w * h);
if (visible > fraction) {
video.play();
} else {
video.pause();
}
}
}
window.addEventListener('scroll', checkScroll, false);
window.addEventListener('resize', checkScroll, false);
}
As explained here, the offsetTop/offsetLeft/etc. approaches are slower and more error prone than the newer getBoundingClientRect approach. Here's some working code to play any videos that are even partially visible in the viewport:
function playVisibleVideos() {
document.querySelectorAll("video").forEach(video => elementIsVisible(video) ? video.play() : video.pause());
}
function elementIsVisible(el) {
let rect = el.getBoundingClientRect();
return (rect.bottom >= 0 && rect.right >= 0 && rect.top <= (window.innerHeight || document.documentElement.clientHeight) && rect.left <= (window.innerWidth || document.documentElement.clientWidth));
}
let playVisibleVideosTimeout;
window.addEventListener("scroll", () => {
clearTimeout(playVisibleVideosTimeout);
playVisibleVideosTimeout = setTimeout(playVisibleVideos, 100);
}, {passive: true});
window.addEventListener("resize", playVisibleVideos);
window.addEventListener("DOMContentLoaded", playVisibleVideos);
The setTimeout stuff ensures that the playVisibleVideos() function isn't called any more often than once every 100ms as the user scrolls (so it doesn't cause lag). The {passive: true} ensures the scroll handler function doesn't "block" scrolling (which can cause scroll lag).
Note that it seems like #Tristanisginger's answer using the more modern IntersectionObserver approach may be a better choice than this one for most people.
This is how I managed to play a video only when the user scrolls to it.
I used IsInViewport plugin.
Hope you find it useful!
$(window).scroll(function() {
var video = $('.yourvideo');
$(video).each(function(){
if(video.is(':in-viewport')){
video[0].play();
video.removeClass('yourvideo');
//I removed class to stop repeating the action ".play()" when it is scrolled again.
}
});
});
In case anyone else runs into this question, I was unable to use Saike's solution on my WordPress site because of the way the videos were auto embedded (MediaElement player). However, qwazix's solution worked with some modification. Here is the jQuery code that works with the IsInView plugin. Here are my include scripts (placed at the end of footer.php in my theme folder).
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="js/isInViewport.min.js" type="text/javascript"></script>
<script src="js/scrollview.min.js" type="text/javascript"></script>
And the jQuery code (modify 400 to your tolerance liking)
$(function() {
$(window).scroll(function() {
$('.wp-video-shortcode').each(function() {
var str = $(this).attr('id');
var arr = str.split('_');
typecheck = arr[0];
if ($(this).is(":in-viewport( 400 )") && typecheck == "mep") {
mejs.players[$(this).attr('id')].media.play();
} else if (typecheck == "mep") {
mejs.players[$(this).attr('id')].media.pause();
}
});
});
});
Only issue I have with this code is that it does restart a video clip on scroll even if paused by the user. Wasn't a deal-breaking issue on my site. Here is the code in action: Ultrasoundoftheweek.com
If you're looking for a simple solution without any dependencies, here it is:
let video = document.getElementById('video')
function playVideoOnScroll () {
const threshold = 300 //px above the video to start playing
let offset = video.getBoundingClientRect().top
if (offset < threshold) {
demoVideo.play()
} else {
demoVideo.pause()
}
}
window.addEventListener('scroll', playVideoOnScroll, false)
window.addEventListener('resize', playVideoOnScroll, false)
My working solution in vanilla 2023 Javascript using IntersectionObserver:
document.addEventListener('DOMContentLoaded', function() {
const videos = document.querySelectorAll('video');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.play();
} else {
entry.target.pause();
}
});
});
videos.forEach(video => {
observer.observe(video);
});
});

Categories