I creating image and i giving file location this image with random number.
I taking these images heights and i saving in sizes array. ıts happening in for loop.
This is generaly working but sometimes sizes being zero.
My codes:
let tests = [];
let sizes = [];
let deger;
for (let index = 0; index < 40; index += 1) {
let img = new Image();
let random = Math.floor(Math.random() * 3);
if(random==0){
deger = '/img/test-1.png';
img.src = deger;
sizes[index]=img.height;
tests[index] = deger;
}else if(random==1){
deger = '/img/test-2.png';
img.src = deger;
sizes[index]=img.height;
tests[index] = deger;
}else{
deger = '/img/test-3.png';
img.src = deger;
sizes[index]=img.height;
tests[index] = deger;
}
}
console.log(sizes);
like this:
The image has not loaded yet so their will not be a height available. Instead you can use the onload method to add them to your array once they are loaded.
Also instead of assigning the sizes at an specific index you could just use the push method
let tests = [];
let sizes = [];
let deger;
for (let index = 0; index < 40; index += 1) {
let img = new Image();
let random = Math.floor(Math.random() * 3);
if(random==0){
deger = 'https://picsum.photos/200';
img.src = deger;
img.onload = function() {
sizes.push(img.height);
tests.push(deger);
console.log(sizes);
}
}else if(random==1){
deger = 'https://picsum.photos/300';
img.src = deger;
img.onload = function() {
sizes.push(img.height);
tests.push(deger);
console.log(sizes);
}
}else{
deger = 'https://picsum.photos/400';
img.src = deger;
img.onload = function() {
sizes.push(img.height);
tests.push(deger);
console.log(sizes);
}
}
}
Related
I'm using Canvas animation for image sequences on the scroll.
And this animation is working fine but I need to reduce the loading time because I'm using almost 884 images for this animation.
So, how can I add section-wise division in this loop? For example, the first 100 images will upload on start and after 5 seconds next 100 images will upload. So every after 5 seconds next 100 images will upload til 884 images.
const html = document.documentElement;
const canvas = document.getElementById("hero-lightpass");
const context = canvas.getContext("2d");
const frameCount = 884;
const currentFrame = index => (
`compressed/${index.toString().padStart(9, 'web_0000')}.webp`
)
const preloadImages = () => {
for (let i = 1; i < frameCount; i++) {
const img = new Image();
img.src = currentFrame(i);
}
};
const img = new Image()
img.src = currentFrame(1);
canvas.width= window.innerWidth;
canvas.height=window.innerHeight;
img.onload=function(){
scaleToFill(this);
}
function scaleToFill(img){
var scale = Math.max(canvas.width / img.width, canvas.height / img.height);
var x = (canvas.width / 2) - (img.width / 2) * scale;
var y = (canvas.height / 2) - (img.height / 2) * scale;
context.drawImage(img, x, y, img.width * scale, img.height * scale);
}
const updateImage = index => {
img.src = currentFrame(index);
}
window.addEventListener('scroll', () => {
const scrollTop = html.scrollTop;
const maxScrollTop = html.scrollHeight - window.innerHeight;
const scrollFraction = scrollTop / maxScrollTop;
const frameIndex = Math.min(
frameCount - 1,
Math.ceil(scrollFraction * frameCount)
);
requestAnimationFrame(() => updateImage(frameIndex + 1))
});
preloadImages()
HTML
<canvas id="hero-lightpass"></canvas>
You can do that with an interval ...
We add a new variable loadedImages and change the preloadImages
let loadedImages = 0
let loadedImages = 0
const frameCount = 884;
const currentFrame = index => (
`compressed/${index.toString().padStart(9, 'web_0000')}.webp`
)
const preloadImages = () => {
for (let i = loadedImages + 1; i < Math.min(loadedImages + 100, frameCount); i++) {
const img = new Image();
img.src = currentFrame(i);
loadedImages++
}
};
setInterval(preloadImages, 5000)
...
preloadImages()
I want to draw an image on the canvas at each iteration, an image coming from an object.
Either I get "not the format HTML..." in the console, or nothing and it blocks the loop.
Is there a way to draw an image on a canvas without putting it first on the index.html, or without loading from an URL?
I tried the two standard solutions and they didn't work.
I didn't find a similar problem using an object property containing the image, to draw it on a canvas.
function Board(width, height) {
this.width = width;
this.height = height;
this.chartBoard = [];
// Création du plateau logique
for (var i = 0; i < this.width; i++) {
const row = [];
this.chartBoard.push(row);
for (var j = 0; j < this.height; j++) {
const col = {};
row.push(col);
}
}
}
let board = new Board(10, 10);
console.log(board);
// CONTEXT OF THE CANVAS
const ctx = $('#board').get(0).getContext('2d');
Board.prototype.drawBoard = function () {
for (var i = 0; i < this.width; i++) {
for (var j = 0; j < this.height; j++) {
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.strokeRect(j * 64, i * 64, 64, 64);
ctx.closePath();
}
}
};
board.drawBoard();
Board.prototype.test = test;
function test() {
console.log(this);
}
// OBJECT TO DRAW
function Obstacle(name, sprite) {
this.name = name;
this.sprite = sprite;
}
const lava = new Obstacle("Lave", "assets/lave.png");
const lava1 = new Obstacle("Lave1", "assets/lave.png");
const lava2 = new Obstacle("Lave2", "assets/lave.png");
const lava3 = new Obstacle("Lave3", "assets/lave.png");
const lava4 = new Obstacle("Lave4", "assets/lave.png");
const lava5 = new Obstacle("Lave5", "assets/lave.png");
const lava6 = new Obstacle("Lave6", "assets/lave.png");
const lava7 = new Obstacle("Lave7", "assets/lave.png");
const lava8 = new Obstacle("Lave8", "assets/lave.png");
const lava9 = new Obstacle("Lave9", "assets/lave.png");
const lavaArray = [lava, lava1, lava2, lava3, lava4, lava5, lava6, lava7, lava8, lava9];
// FUNCTION TO DRAW
Board.prototype.setPiece = function (piece) {
let randomX = Math.floor(Math.random() * board.width);
let randomY = Math.floor(Math.random() * board.height);
let drawX = randomX * 64;
let drawY = randomY * 64;
if (randomX >= this.width || randomY >= this.height) {
throw new Error('Pièce hors limite');
}
if (piece instanceof Obstacle) {
if (!(this.chartBoard[randomY][randomX] instanceof Obstacle)) {
this.chartBoard[randomY][randomX] = piece;
// CODE TO DRAW, BUG DOESN'T WORK
ctx.fillRect(drawX, drawY,64,64);
let image = Obstacle.sprite;
ctx.drawImage = (image, drawX, drawY);
}
}
} else {
throw new Error('Pièce non valide');
}
};
Board.prototype.setObstacles = function () {
for (let lava of lavaArray) {
const obstacle = board.setPiece(lava);
}
};
board.setObstacles();
Actual: No image is drawn. And if I try fillRect, it works well. So the loop works.
Expected: Be able to draw an image on a canvas from an object property.
It's not really clear what you're trying to do.
The code you have commented
ctx.drawImage = (image, drawX, drawY);
should be this
ctx.drawImage(image, drawX, drawY);
Looking a little broader you have this
let image = Obstacle.sprite;
ctx.drawImage(image, drawX, drawY); // assume this was fixed
But Obstacle is a class, not an instance of that class. You want
let image = piece.sprite;
ctx.drawImage(image, drawX, drawY);
But that leads the next issue. looking at the rest of the code piece.sprite is a string not an image. See this code.
// OBJECT TO DRAW
function Obstacle(name, sprite) {
this.name = name;
this.sprite = sprite;
}
const lava = new Obstacle("Lave", "assets/lave.png");
There are a several ways you can draw images to a canvas. If they come from a file you do have to wait for them to download. Otherwise you can generate them from another canvas. You can also use createImageData and putImageData as another way to make images.
Let's change the code to load a bunch of images and then start
I moved all the class code to the top and the start up code to the bottom.
There were a few places inside Board methods where the global variable board was used instead of this so I fixed those.
Here`s a function that loads an image and returns a Promise
function loadImage(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => { resolve(img); };
img.onerror = reject;
img.crossOrigin = 'anonymous'; // REMOVE IF SAME DOMAIN!
img.src = url;
});
}
You could use that to load one image like this
loadImage(urlOfImage).then(function(img) {
// use the loaded img
});
I used that function to write this function that takes an object of names to urls and returns an object of names to loaded images.
function loadImages(images) {
return new Promise((resolve) => {
const loadedImages = {};
const imagePromises = Object.entries(images).map((keyValue) => {
const [name, url] = keyValue;
return loadImage(url).then((img) => {
loadedImages[name] = img;
});
});
Promise.all(imagePromises).then(() => {
resolve(loadedImages);
});
});
}
I then call that and pass the object of names to loaded images to the start function. Only one image is loaded at the moment but you can add more.
const images = {
lave: 'https://i.imgur.com/enx5Xc8.png',
// player: 'foo/player.png',
// enemy: 'foo/enemny.png',
};
loadImages(images).then(start);
// CONTEXT OF THE CANVAS
const ctx = $('#board').get(0).getContext('2d');
function Board(width, height) {
this.width = width;
this.height = height;
this.chartBoard = [];
// Création du plateau logique
for (var i = 0; i < this.width; i++) {
const row = [];
this.chartBoard.push(row);
for (var j = 0; j < this.height; j++) {
const col = {};
row.push(col);
}
}
}
Board.prototype.drawBoard = function () {
for (var i = 0; i < this.width; i++) {
for (var j = 0; j < this.height; j++) {
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.strokeRect(j * 64, i * 64, 64, 64);
ctx.closePath();
}
}
};
// OBJECT TO DRAW
function Obstacle(name, sprite) {
this.name = name;
this.sprite = sprite;
}
// FUNCTION TO DRAW
Board.prototype.setPiece = function (piece) {
let randomX = Math.floor(Math.random() * this.width);
let randomY = Math.floor(Math.random() * this.height);
let drawX = randomX * 64;
let drawY = randomY * 64;
if (randomX >= this.width || randomY >= this.height) {
throw new Error('Pièce hors limite');
}
if (piece instanceof Obstacle) {
if (!(this.chartBoard[randomY][randomX] instanceof Obstacle)) {
this.chartBoard[randomY][randomX] = piece;
// CODE TO DRAW, BUG DOESN'T WORK
ctx.fillRect(drawX, drawY,64,64);
let image = piece.sprite;
ctx.drawImage(image, drawX, drawY);
}
} else {
throw new Error('Pièce non valide');
}
};
Board.prototype.setObstacles = function (lavaArray) {
for (let lava of lavaArray) {
const obstacle = this.setPiece(lava);
}
};
function start(images) {
let board = new Board(10, 10);
// console.log(board);
const lava = new Obstacle("Lave", images.lave);
const lava1 = new Obstacle("Lave1", images.lave);
const lava2 = new Obstacle("Lave2", images.lave);
const lava3 = new Obstacle("Lave3", images.lave);
const lava4 = new Obstacle("Lave4", images.lave);
const lava5 = new Obstacle("Lave5", images.lave);
const lava6 = new Obstacle("Lave6", images.lave);
const lava7 = new Obstacle("Lave7", images.lave);
const lava8 = new Obstacle("Lave8", images.lave);
const lava9 = new Obstacle("Lave9", images.lave);
const lavaArray = [lava, lava1, lava2, lava3, lava4, lava5, lava6, lava7, lava8, lava9];
board.drawBoard();
board.setObstacles(lavaArray);
}
function loadImage(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => { resolve(img); };
img.onerror = reject;
img.crossOrigin = 'anonymous'; // REMOVE IF SAME DOMAIN!
img.src = url;
});
}
function loadImages(images) {
return new Promise((resolve) => {
const loadedImages = {};
// for each name/url pair in image make a promise to load the image
// by calling loadImage
const imagePromises = Object.entries(images).map((keyValue) => {
const [name, url] = keyValue;
// load the image and when it's finished loading add the name/image
// pair to loadedImages
return loadImage(url).then((img) => {
loadedImages[name] = img;
});
});
// wait for all the images to load then pass the name/image object
Promise.all(imagePromises).then(() => {
resolve(loadedImages);
});
});
}
const images = {
lave: 'https://i.imgur.com/enx5Xc8.png',
// player: 'foo/player.png',
// enemy: 'foo/enemny.png',
};
loadImages(images).then(start);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="board" width="640" height="640"></canvas>
I am trying to compare different blocks of an image(filled.png) with a specific block of another image(blank.png).
So far I have tried this :-
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = 20;
canvas.height = 20;
var img = new Image();
img.onload = function(){
context.drawImage(img,53,61,20,20,0,0,20,20);
};
img.src ='blank.png';
var imgResult = new Image();
var image1,image2;
var canvasResult = document.createElement('canvas');
canvasResult.width = 20;
canvasResult.height = 20;
var contextResult = canvasResult.getContext('2d');
function compare(){
image1=new Image();
image1.onload= function(){
imgResult.onload = function(){
var x = 53;
for (var i = 1; i <= 20; i++) {
contextResult.clearRect(0, 0, 20, 20);
contextResult.drawImage(imgResult,x,61,20,20,0,0,20,20);
x += 23;
image2 = new Image();
image2.onload = function(){
resemble(image1.src).compareTo(image2.src).onComplete(function(data){
$('p').append('Diffrence : ' + data.misMatchPercentage+ '%</br>');
});
};
image2.src = canvasResult.toDataURL();
}
};
imgResult.src = 'filled.png';
}
image1.src=canvas.toDataURL();
}
But it is not working, getting same result on each iteration of for loop. So please help me find, where I am going wrong.
.onComplete - sounds asynchronous, and image2.onload DEFINITELY IS - but in the meantime you're changing contextResult ... asynchronous code strikes again
If you create a function which recursively calls itself when each iteration completes, you should have better results:
e.g. with minimal code changes to what you have:
imgResult.onload = function(){
var x = 53, i = 1;
var compare = function() {
contextResult.clearRect(0, 0, 20, 20);
contextResult.drawImage(imgResult,x,61,20,20,0,0,20,20);
x += 23;
image2 = new Image();
image2.onload = function(){
resemble(image1.src).compareTo(image2.src).onComplete(function (data) {
$('p').append('Diffrence : ' + data.misMatchPercentage+ '%</br>');
i += 1;
if (i <= 20) {
compare();
}
});
};
image2.src = canvasResult.toDataURL();
};
compare();
}
I have the below base64 encoded string which contains the pdf file.
I want to convert the base64 string to a Uint8Array as Uint8Array is supported from IE9 forward, and than I want to open pdf using pdf.js
I am using following code,
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
var pdfAsDataUri = "data:application/pdf;base64," + base64encodedString;
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)
base64encodedString = JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9MZW5ndGggMTE1My9GaWx0ZXIvRmxhdGVEZWNvZGU+PnN0cmVhbQp4nI2XbW/bNhDH3/tT8NXQAavCJ1HigAF17SRI29hNrHR7y1lsp8CWXYne5m+/k2R5NcVTgiKok//97o6n4+n8ffI+mwhFkiQhWT6h5C1n/adEnT4w2n+Scf8nJZtP19nkYfK9/eHkAwi3ExrF5J9JmkaCJIoSRmWkCPis7GR1EpnmkW5VwUSUemqHSjGGgoqjXI2hoOIo1WMoqCiqNB9BGxVHk3gMBRVH43QMBRVHJRtDQcVRLsdQUHGUJmMoqCga67FuatRL9KFpbUYo/GNE07YfoX23k6ub5uQk+zp588WW+a4iC7O1v/6cPTf9/APEtGz71KemZE5WT1m2XJCfyGq5WA3RLp5Mw/Fmu9KZtcNDDsAPtiyP5JPZYqEEC4e63ppigwcaYM9NoHf1YW8rV4GLonSbaL1D4zIZjjvN88rWNR55AHJKfr9eZUSIRyhv9nh9nSFBlU489gaquauO4w9yiN1+WmZ3U3I/XTzdTGfZ0+Pd4pbMlvefscApRQK/9ESHpDHmXV7XI7VVSnjMXVnv7doVuxICbvemPOIBB/D7Q2XNgXyxVeFMjcWUym/2Q17AEfFAA+LfNeaca8/00e53lSOLw/ZPOxJiwOEhGMdrNjdupDsGJKNXTF9xymIkWKwHk6EpFsmOezzOEJr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Q0YjVhMzZkZGEwZjJmMDMzZGJiPl0vSW5mbyA3IDAgUi9TaXplIDg+PgpzdGFydHhyZWYKMTg5OAolJUVPRgo=
But pdf is not getting generated or open in browser, any kind of suggestions or help will be appreciated.
I use this in my projects and it works fine.
HTML
<div id="myCanvasContainer"></div>
JS
function renderPDF( pdfBase64 ) {
var pdfUint8Array = base64ToUint8Array( pdfBase64 );
var canvasContainer = document.getElementById('myCanvasContainer');
var options = options || { scale: 1.5 };
function renderPage(page) {
var viewport = page.getViewport(options.scale);
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
canvas.height = viewport.height;
canvas.width = viewport.width;
canvasContainer.appendChild(canvas);
page.render(renderContext);
}
function renderPages(pdfDoc) {
for(var num = 1; num <= pdfDoc.numPages; num++)
pdfDoc.getPage(num).then(renderPage);
}
function base64ToUint8Array(base64) {
var raw = atob(base64);
var uint8Array = new Uint8Array(raw.length);
for (var i = 0; i < raw.length; i++) {
uint8Array[i] = raw.charCodeAt(i);
}
return uint8Array;
}
PDFJS.disableWorker = true;
PDFJS.getDocument(pdfUint8Array).then(renderPages);
}
Hope it helps.
What I am trying to do is load images dynamically and then draw them on the screen. However, when I call console.log(images), it is empty.
Here is the code:
if (canvas.getContext)
{
var ctx = canvas.getContext("2d");
var images = new Array();
for (i = 0; i < mattes_array.length; i++)
{
var imgsrc = mattes_array[i]["imgsrc"];
var total_size = mattes_array[i]["total_size"];
var cpu = mattes_array[i]["cpu"];
var cid = mattes_array[i]["cid"];
var imageObj = new Image();
imageObj.onload = function() {
images[i] = imageObj;
console.log(images[i]);
};
imageObj.id = "matte_" + cid;
imageObj.src = imgsrc;
}
console.log(images); //this is empty
for (i = 0; i < mattes_array.length; i++)
{
var imgsrc = mattes_array[i]["imgsrc"];
var total_size = mattes_array[i]["total_size"];
var cpu = mattes_array[i]["cpu"];
var cid = mattes_array[i]["cid"];
var pattern = ctx.createPattern(images[i], 'repeat');
ctx.strokeStyle = pattern;
ctx.lineWidth = width - opening_width - (total_size * 2);
ctx.strokeRect(0, 0, width, height);
}
}
I have also tried doing it in one loop, but it seems to only draw the last image:
if (canvas.getContext)
{
var ctx = canvas.getContext("2d");
var images = new Array();
for (i = 0; i < mattes_array.length; i++)
{
var imgsrc = mattes_array[i]["imgsrc"];
var total_size = mattes_array[i]["total_size"];
var cpu = mattes_array[i]["cpu"];
var cid = mattes_array[i]["cid"];
var imageObj = new Image();
imageObj.onload = function() {
var pattern = ctx.createPattern(imageObj, 'repeat');
ctx.strokeStyle = pattern;
ctx.lineWidth = width - opening_width - (total_size * 2);
ctx.strokeRect(0, 0, width, height);
};
imageObj.id = "matte_" + cid;
imageObj.src = imgsrc;
}
}
Here is an image of what I am trying to do:
Images load asynchronously. You're trying to draw them before they are loaded. Give this a try:
if (canvas.getContext)
{
var ctx = canvas.getContext("2d");
var images = new Array();
var loaded = 0;
for (i = 0; i < mattes_array.length; i++)
{
var imgsrc = mattes_array[i]["imgsrc"];
var total_size = mattes_array[i]["total_size"];
var cpu = mattes_array[i]["cpu"];
var cid = mattes_array[i]["cid"];
var imageObj = new Image();
imageObj.onload = function() {
images[i] = imageObj;
console.log(images[i]);
if ( ++loaded === mattes_array.length ) onloaded();
};
imageObj.id = "matte_" + cid;
imageObj.src = imgsrc;
}
function onloaded() {
console.log(images); //this is won't be empty anymore
for (i = 0; i < mattes_array.length; i++)
{
var imgsrc = mattes_array[i]["imgsrc"];
var total_size = mattes_array[i]["total_size"];
var cpu = mattes_array[i]["cpu"];
var cid = mattes_array[i]["cid"];
var pattern = ctx.createPattern(images[i], 'repeat');
ctx.strokeStyle = pattern;
ctx.lineWidth = width - opening_width - (total_size * 2);
ctx.strokeRect(0, 0, width, height);
}
}
}