How do I preload my image array via javascript - arrays

I would like to have some advice on how to best preload my image array in javascript.
I've been reading some other solutions but as someone new I'm having some problem on how to implement them in my existing code.
Thank you.
const layerImage = {
1:'https://plateau.ar/story/scroll/images/Video401.png',
2:'https://plateau.ar/story/scroll/images/Video402.png',
3:'https://plateau.ar/story/scroll/images/Video403.png',
4:'https://plateau.ar/story/scroll/images/Video404.png',
5:'https://plateau.ar/story/scroll/images/Video405.png',
68:'https://plateau.ar/story/scroll/images/Video468.png',
69:'https://plateau.ar/story/scroll/images/Video469.png',
70:'https://plateau.ar/story/scroll/images/Video470.png',
71:'https://plateau.ar/story/scroll/images/Video471.png',
72:'https://plateau.ar/story/scroll/images/Video472.png',
73:'https://plateau.ar/story/scroll/images/Video473.png',
74:'https://plateau.ar/story/scroll/images/Video474.png',
}
function checkScroll() {
const y = window.scrollY;
const scrollPixels = Math.min(Math.floor(y/100) + 1, 74);
const imageToUse = layerImage[scrollPixels];
// Change the background image
$('.imageBox').css('background-image', `url('${imageToUse}')`);
}
$(document).ready(()=>{
$(window).scroll(()=>{
checkScroll();
})
})

Related

Three js change color on press button removes the details of the model

Hope you all are doing best in you life!
I've newly intraction with 3d work. I'm making the 3d virtual showroom you can say 3d commerce page,where i need to put 3d Models. I want to add functionality of changing models color (limited colors) by users. like this: [https://codesandbox.io/s/v1fgk].(I'm using three js not react three fiber.)
THREE JS Version: "three": "^0.135.0",
The problem is that:
1) When i change the color of the mesh the details of the model are deleted.what can i do for this?
2) I face alot of lighting issues during this work.finally I'm using HDRI envornment instead of lighting in my models.
am i doing best?
Actual Model:
On Change Color:
Why my models's details are going to delete?
On Changing Color i'm doing this:
// const loader = new THREE.TextureLoader();
// const aoTexture = loader.load('textures/BottleModel/Model2/Material.002_Mixed_AO.png')
// const displacementTexture = loader.load('textures/BottleModel/Model2/base_Height.png')
// const metalicTexture = loader.load('textures/BottleModel/Model2/Material.002_Metallic.png')
// const roughnessTexture = loader.load('textures/BottleModel/Model2/Material.002_Roughness.png')
const BottleMesh=model.current.children.find((item)=>item.name==="cup_base")
BottleMesh.children.map((item)=>{
if(item.name==="Cylinder"){
item.material = new THREE.MeshStandardMaterial({
color: code,
// aoMap:aoTexture,
// metalnessMap : metalicTexture,
// displacementMap:displacementTexture,
// roughnessMap:roughnessTexture
})
}
})
CREATING MODEL AND ADDING ENVORNMENT:
export const createModel = (model, scene, path, setLoading,renderer) => { //model is a react ref, remember that
setLoading(true)
const dracoLoader = new DRACOLoader();
// // Specify path to a folder containing WASM/JS decoding libraries.
dracoLoader.setDecoderPath('https://www.gstatic.com/draco/v1/decoders/');
let loader = new GLTFLoader();
loader.setDRACOLoader(dracoLoader);
let generator = new THREE.PMREMGenerator(renderer);
new RGBELoader().setPath('/textures/hdri/') .load('dancing_hall_4k.hdr', function (texture) {
// let envmap =generator.fromEquirectangular(texture)
texture.mapping = THREE.EquirectangularReflectionMapping;
// scene.background = texture;
scene.environment = texture;
});
loader.load(path, function (gltf) {
model.current = gltf.scene;
model.current.position.x=0
model.current.position.y=-3
scene.add(model.current);
setLoading(false);
}, undefined, function (error) {
console.error(error)
});
}

Can I remove parameter from URL generated by video playlist in Elementor

Elementor Pro has a new widget, video playlist. It appends a parameter to the URL, like so: http://aaronpenton.net/ampcreative/vip/about-vip/?playlist=f68425e&video=b8a9967
This is obviously terrible for SEO and UX. Is there a way to remove the ?playlist=f68425e&video=b8a9967 ?
My brother help me with the next script.
Put a "HTML Elementor Widget" with the following:
<script>
function getURLParameter(name) {
return decodeURI((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]);
}
function hideURLParams() {
//Parameters to hide (ie ?playlist=value, ?video=value, etc)
var hide = ['playlist','video'];
for(var h in hide) {
if(getURLParameter(h)) {
history.replaceState(null, document.getElementsByTagName("title")[0].innerHTML, window.location.pathname);
}
}
}
window.onload = hideURLParams;
</script>
This should do the trick.
const url = 'http://aaronpenton.net/ampcreative/vip/about-vip/?playlist=f68425e&video=b8a9967'
url.replace(url.split('/')[6], '')
split, well.. splits the string into an array by the /
character.
At index 6 the array contains the ?playlist=f68425e&video=b8a9967 substring which can than be removed (i.e. replaced by the empty string) using replace.
A more general approach to removing the last part of the url might
be to use the array length instead of specifying the index:
const url = 'http://aaronpenton.net/ampcreative/vip/about-vip/?playlist=f68425e&video=b8a9967'
const urlArr = url.split('/')
url.replace(urlArr[urlArr.length - 1], '')
Update:
Another way to do this is using the URL API
const url = new URL('http://aaronpenton.net/ampcreative/vip/about-vip/?playlist=f68425e&video=b8a9967');
const result = url.origin + url.pathname
or in a function:
const removeParameter = u => {
const url = new URL(u);
return url.origin + url.pathname
}
You might have to check the specification for further details (browser support etc)

Upload Image Width and Height get in react

I am new to React and react hook I want to upload an image from anywhere but I want to know the width and height of a select image before storing it in the database. I want to store the original image metadata width and height. anyone can help me
One solution can be to use FileReader, something like this should work:
const image = new Image();
let fr = new FileReader();
fr.onload = function() {
if (fr !== null && typeof fr.result == "string") {
image.src = fr.result;
}
};
fr.readAsDataURL(inputFile);
image.onload = async function() {
const width = image.width;
};
You can take a look here: https://github.com/toncic/Image-Classification/blob/master/src/Components/ImageClassification.tsx#L45

how to fix this Error Cannot use the same canvas during multiple render() operations

I am using canvas in react and rendering pdf's as images using the canvas.
Now, when I get new data i.e another pdf get's added, then
again have to use the canvases for that.
I am not sure how to fix this error or how to remove the canvas or even clear the canvas before using it again.
Here's the relevant code:
pdfLoop = (item,index) => {
var that = this;
PDFJS.getDocument(item).then(function getPdfHelloWorld(pdf) {
//
// Fetch the first page
console.log('url is : ',item);
pdf.getPage(1).then(function getPageHelloWorld(page) {
var scale = 0.5;
var viewport = page.getViewport(scale);
let cref = 'canvas'+index;
let imgref ='img'+index;
console.log('cref no : ',cref);
console.log('img no : ',imgref);
// Prepare canvas using PDF page dimensions
//
var canvas = that.canvasRefs[cref];
//let imagez = that.imageRefs[imgref];
var context = canvas.getContext('2d');
context.globalcompositeoperation = 'source-over';
// context.fillStyle = "#fff";
//draw on entire canvas
//context.fillRect( 0, 0, canvas.width, canvas.height );
canvas.height = viewport.height;
canvas.width = viewport.width;
//imagez.src = canvas.toDataURL("image/png");
//
// Render PDF page into canvas context
//
//page.render({canvasContext: context, viewport: viewport});
var task = page.render({canvasContext: context, viewport: viewport})
task.promise.then(function(){
//console.log(canvas.toDataURL('image/png'));
let imgItem = {imgref:canvas.toDataURL('image/png'),page:index+1,rotate:0}
let newState = that.state.imgsrc;
newState[index] = imgItem;
//let newState = that.state.imgsrc.concat(imgItem);
that.setState({
imgsrc:newState
});
//imagez.src = canvas.toDataURL('image/png')
});
});
});
}
In case someone stumbles across this, the error message states the following Use different canvas or ensure previous operations were cancelled or completed.
When getting the document, if there already is a document, it has to be destroyed. I.e:
PDFJS.getDocument({ url: pdf_url }).promise
.then((pdf_doc) => {
if (this.pdf_doc) {
this.pdf_doc.destroy();
}
this.pdf_doc = pdf_doc;
this.total_pages = this.pdf_doc.numPages;
})
I have no idea if this is a good solution, but at least it worked for me.
I've had the same exact problem as you, but my solution was a bit different than the answers previously posted.
For me the problem was the fact that I was unnecessarily re-rendering with a state change. Check if you aren't re-rendering the component without properly clearing the canvas, or if you even need to re-render at all (in my case I didn't).
Hopefully this could help
In order to avoid this situation, put your canvas object in a div object as is shown below:
<div id="div_canvas">
<canvas id="cnv"></canvas>
</div>
Then, before to call pdf.js functions, remove the "div_canvas" content and recreate it:
$("#div_canvas").html("");
$("#div_canvas").html("<canvas id='cnv'></canvas>");
I had exactly the same issue when working with PDF.js, the solution to this is,
You will have to clear your context after the render completes.
if (context) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
}
This will make sure that the context is cleared and ready for the next render and the error disappears.
this worked for me.
In some cases, this error will be displayed when the pdf has action buttons such as next/previous or scaling.
In this cases, often you have a function for rendering pdf page such as:
renderPage(num) {
// Using promise to fetch the page
pdfDoc.getPage(num).then(function (page) {
const viewport = page.getViewport({scale: scale});
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
const renderContext = {
canvasContext: ctx,
viewport: viewport
};
page.render(renderContext);
});
}
To fix the error just perform following changes:
Add two variable for controlling conflict and cache waiting page number:
pageRendering = false; // Check conflict
pageNumPending = null; // Cache waiting page number
Use these variables as follow:
renderPage(num) {
if (this.pageRendering) { // Check if other page is rendering
this.pageNumPending = num; // Cache waited page number until previous page rendering completed
} else {
this.pageRendering = true;
// Using promise to fetch the page
pdfDoc.getPage(num).then(function (page) {
const viewport = page.getViewport({scale: scale});
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
const renderContext = {
canvasContext: ctx,
viewport: viewport
};
const renderTask = page.render(renderContext);
// Wait for rendering to finish
renderTask.promise.then(function () {
this.pageRendering = false;
if (pageNumPending !== null) {
// Waited page must be rendered
this.renderPage(pageNumPending);
// Must be set to null to prevent infinite loop
this.pageNumPending = null;
}
});
});
One possible cause: React Strict mode renders twice

Adding Entity into its own block in DraftJS

So I'm trying to create a fairly simple WYSIWYG BBCode editor for my project as an opportunity to wrap my mind around DraftJS. I've been following some tutorials and also using react-rte as an example (since it has 99% of the functionality I need and looks relatively simple to understand).
The problem I've stumped on is that react-rte inserts image entities inline (it adds a space in the current selection and then ties an entry to that space) like this:
const addEntity = (editorState, type, mutability = 'MUTABLE', data = {}) => {
let currentContent = editorState.getCurrentContent();
let selection = editorState.getSelection();
currentContent = currentContent.createEntity(type, mutability, data);
let entityKey = currentContent.getLastCreatedEntityKey();
return Modifier.insertText(currentContent, selection, ' ', null, entityKey);
}
I want each image (and video alike) to be in its own separate block and make it so nothing else can be written to that block.
I have found an example of the behavior I'm after in megadraft, but I have been unable to work my way through its code to find the correct implementation.
Found the solution after many hours of trial and error (and lots of manuals).
const addAtomic = (editorState, type, mutability = 'MUTABLE', data = {}) => {
let currentContent = editorState.getCurrentContent();
let selection = editorState.getSelection();
currentContent = currentContent.createEntity(type, mutability, data);
let entityKey = currentContent.getLastCreatedEntityKey();
const newState = EditorState.set(editorState, { currentContent: currentContent })
return AtomicBlockUtils.insertAtomicBlock(newState, entityKey, ' ')
}

Resources