I'm using canvas for this animation. The animation is working fine on localhost but on the live servers it's taking too much time.
This is because I'm using almost 3000 frames for this animation, all frames are important. How can I increase the loading speed on the live server?
I have attached the code. Please review it and help me if I'm wrong somewhere.
const html = document.documentElement;
const canvas = document.getElementById("hero-lightpass");
const context = canvas.getContext("2d");
const frameCount = 2999;
const currentFrame = index => (`compressed/${index.toString().padStart(9, '720_0000')}.jpg`)
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);
context.drawImage(img, 0, 0);
}
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()
<canvas id="hero-lightpass"></canvas>
There might be some edge cases where you still need individual images, and the suggestions in the comments (using video or Sprite sheets) will not do, if you can use one of those option you should, it will simplify a lot...
I'm going to focus on that edge case where we have a ton of images
Great examples how to do things like that are online maps:
Google maps (https://www.google.com/maps)
OpenStreetMap (https://www.openstreetmap.org/)
Those maps have a lot of images, but they do not download all at once, they download and draw only what is needed, in your case you can preload maybe 50 (you have to experiment to see what best) and download the 51, 52 ... as you are drawing the first you have preloaded.
Back to the maps; They use "small" map tiles to paint one big mosaic, here are a couple of tiles:
https://a.tile.openstreetmap.org/6/16/25.png
https://b.tile.openstreetmap.org/6/15/26.png
You can see they are coming from different servers a & b that is to speed up download, browsers have limits on how many images are downloaded from one server at a time, for more details see:
http://kb.mozillazine.org/Network.http.max-connections-per-server
In a nutshell:
Download and draw only what is needed
Use multiple servers to host your images
Related
I need to download the created pixel drawing from this Phaser example as a .png image via FilesSaver.js but the canvas returns null.
Error:
Uncaught TypeError: Cannot read properties of null (reading 'toBlob')
This is the save function:
function save() {
var canvasX = document.getElementById("canvas");
canvasX.toBlob(function(blob) { saveAs(blob, "image.png"); }); }
drawingArea: (PhaserJS 2)
function createDrawingArea() {
game.create.grid('drawingGrid', 16 * canvasZoom, 16 * canvasZoom, canvasZoom, canvasZoom, 'rgba(0,191,243,0.8)');
canvas = game.make.bitmapData(spriteWidth * canvasZoom, spriteHeight * canvasZoom);
canvasBG = game.make.bitmapData(canvas.width + 2, canvas.height + 2);
canvasBG.rect(0, 0, canvasBG.width, canvasBG.height, '#fff');
canvasBG.rect(1, 1, canvasBG.width - 2, canvasBG.height - 2, '#3f5c67');
var x = 10;
var y = 64;
canvasBG.addToWorld(x, y);
canvasSprite = canvas.addToWorld(x + 1, y + 1);
canvasGrid = game.add.sprite(x + 1, y + 1, 'drawingGrid');
canvasGrid.crop(new Phaser.Rectangle(0, 0, spriteWidth * canvasZoom, spriteHeight * canvasZoom));
}
How to get the data of the drawing to create a .png out of it?
Well I don't think the canvas has the ID canvas. That's why, I asume that is the reason for the null Error.
In any case I took the original example code, as a basis for this working solution.
Disclaimer: This Code will only create a image from the "drawn-image", not the whole UI.
Main idea, On Save:
create a new canvas
draw the target area into the new canvas
create the image, with filesave.js
Info: I'm getting information/values from the the globally defined variables canvasGrid and canvas, if your code, doesn't contain them, this code will not work.
I hope this helps.
function saveImage() {
// I assume there will be only one canvas on the page
let realCanvas = document.querySelector('canvas');
let ouputCanvas = document.createElement('canvas');
let ctx = ouputCanvas.getContext('2d');
// Get the target area (Details are from example code)
let xOfGrid = canvasGrid.x - 1; // Info from Linie 267 from example
let yOfGrid = canvasGrid.y - 1; // Info from Linie 267 from example
// Info: this "canvas" is not a HTML Canvas Element
let width = canvas.width; // Info from Linie 256 from example
let height = canvas.height; // Info from Linie 256 from example
// Set initial Canvas Size
ouputCanvas.width = width;
ouputCanvas.height = height;
// draw Image onto new Canvas
ctx.drawImage(realCanvas, xOfGrid, yOfGrid, width, height, 0, 0, width, height);
// Output Image, with filesaver.js
ouputCanvas.toBlob(function onDone(blob) {
saveAs(blob, "image.png");
});
}
// An extra "Save Button", for testing
window.addEventListener('DOMContentLoaded', function(){
let btn = document.createElement('button');
btn.innerText = 'SAVE FILE';
btn.addEventListener('click', saveImage);
document.body.prepend( btn );
});
Introduction
I'm trying to deal with blurry visuals on my canvas animation. The blurriness is especially prevalent on mobile-devices, retina and high-dpi (dots-per-inch) screens.
I'm looking for a way to ensure the pixels that are drawn using the canvas look their best on low-dpi screens and high-dpi screens. As a solution to this problem I red multiple articles about canvas-down-scaling and followed this tutorial:
https://www.kirupa.com/canvas/canvas_high_dpi_retina.htm
Integrating down-scaling in the project
The project in which I want to implement down-scaling can be found below and consists of a few important features:
There is a (big) main canvas. (Performance optimization)
There are multiple (pre-rendered) smaller canvasses that are used to draw and load a image into. (Performance optimization)
The canvas is animated. (In the code snippet, there is no visible animation but the animation function is intergrated.)
Question
What im trying to achieve: The problem I'm facing seems quite simple. When the website (with the canvas) is opened on a mobile device (eg. an Iphone, with more pixels per inch then a regular desktop). The images appear more blurry. What I'm actually trying to achieve is to remove this blurriness from the images. I red this and it stated that blurriness can be removed by downsampling. I tried to incorporate this technique in the code provided, but it did not work completely. The images just became larger and I was unable to scale the images back to the original size. snippet it is not implemented correctly, the output is still blurry. What did I do wrong and how am I able to fix this issue?
Explanation of the code snippet
The variable devicePixelRatio is set to 2 to simulate a high-dpi phone screen, low-dpi screens have a devicePixelRatio of 1.
Multiple pre-rendered canvasses generated is the function spawn is the snippet there are 5 different canvasses, but on the production environment there are 10's.
If there are any pieces of information missing or questions about this post, please let me know. Thanks a lot!
Code Snippet
var canvas = document.querySelector('canvas');
var c = canvas.getContext('2d' );
var circles = [];
//Simulate Retina screen = 2, Normal screen = 1
let devicePixelRatio = 2
function mainCanvasPixelRatio() {
// get current size of the canvas
let rect = canvas.getBoundingClientRect();
// increase the actual size of our canvas
canvas.width = rect.width * devicePixelRatio;
canvas.height = rect.height * devicePixelRatio;
// ensure all drawing operations are scaled
c.scale(devicePixelRatio, devicePixelRatio);
// scale everything down using CSS
canvas.style.width = rect.width + 'px';
canvas.style.height = rect.height + 'px';
}
// Initial Spawn
function spawn() {
for (let i = 0; i < 2; i++) {
//Set Radius
let radius = parseInt(i*30);
//Give position
let x = Math.round((canvas.width/devicePixelRatio) / 2);
let y = Math.round((canvas.height /devicePixelRatio) / 2);
//Begin Prerender canvas
let PreRenderCanvas = document.createElement('canvas');
const tmp = PreRenderCanvas.getContext("2d");
//Set PreRenderCanvas width and height
let PreRenderCanvasWidth = ((radius*2)*1.5)+1;
let PreRenderCanvasHeight = ((radius*2)*1.5)+1;
//Increase the actual size of PreRenderCanvas
PreRenderCanvas.width = PreRenderCanvasWidth * devicePixelRatio;
PreRenderCanvas.height = PreRenderCanvasHeight * devicePixelRatio;
//Scale PreRenderCanvas down using CSS
PreRenderCanvas.style.width = PreRenderCanvasWidth + 'px';
PreRenderCanvas.style.height = PreRenderCanvasHeight + 'px';
//Ensure PreRenderCanvas drawing operations are scaled
tmp.scale(devicePixelRatio, devicePixelRatio);
//Init image
const image= new Image();
//Get center of PreRenderCanvas
let m_canvasCenterX = (PreRenderCanvas.width/devicePixelRatio) * .5;
let m_canvasCenterY = (PreRenderCanvas.height/devicePixelRatio) * .5;
//Draw red circle on PreRenderCanvas
tmp.strokeStyle = "red";
tmp.beginPath();
tmp.arc((m_canvasCenterX), (m_canvasCenterY), ((PreRenderCanvas.width/devicePixelRatio)/3) , 0, 2 * Math.PI);
tmp.lineWidth = 2;
tmp.stroke();
tmp.restore();
tmp.closePath()
//Set Image
image .src= "https://play-lh.googleusercontent.com/IeNJWoKYx1waOhfWF6TiuSiWBLfqLb18lmZYXSgsH1fvb8v1IYiZr5aYWe0Gxu-pVZX3"
//Get padding
let paddingX = (PreRenderCanvas.width/devicePixelRatio)/5;
let paddingY = (PreRenderCanvas.height/devicePixelRatio)/5;
//Load image
image.onload = function () {
tmp.beginPath()
tmp.drawImage(image, paddingX,paddingY, (PreRenderCanvas.width/devicePixelRatio)-(paddingX*2),(PreRenderCanvas.height/devicePixelRatio)-(paddingY*2));
tmp.closePath()
}
let circle = new Circle(x, y, c ,PreRenderCanvas);
circles.push(circle)
}
}
// Circle parameters
function Circle(x, y, c ,m_canvas) {
this.x = x;
this.y = y;
this.c = c;
this.m_canvas = m_canvas;
}
//Draw circle on canvas
Circle.prototype = {
//Draw circle on canvas
draw: function () {
this.c.drawImage( this.m_canvas, (this.x - (this.m_canvas.width)/2), (this.y - this.m_canvas.height/2));
}
};
// Animate
function animate() {
//Clear canvas each time
c.clearRect(0, 0, (canvas.width /devicePixelRatio), (canvas.height /devicePixelRatio));
//Draw in reverse for info overlap
circles.slice().reverse().forEach(function( circle ) {
circle.draw();
});
requestAnimationFrame(animate);
}
mainCanvasPixelRatio()
spawn()
animate()
#mainCanvas {
background:blue;
}
<canvas id="mainCanvas"></canvas>
<br>
<!DOCTYPE html>
<html>
<body>
<p>Image to use:</p>
<img id="scream" width="220" height="277"
src="pic_the_scream.jpg" alt="The Scream">
<p>Canvas:</p>
<canvas id="myCanvas" width="240" height="297"
style="border:1px solid #d3d3d3;">
</canvas>
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 10, 10);
};
</script>
</body>
In a web application I'm using JSPDF to convert the html to pdf. All works fine, except for the images. After a while, I noticed that it adds images that point to a local resource; instead, it does not add images that point to an online resource, and leaves in the place of the image an empty space, as if he expected it but could not load it.
For example: <img src="img/house.jpg"/> is correctly added.
<img src="https://myurl.com/house.jpg"/> is not correctly added; there is an empty space instead of the image.
How can I solve it? Maybe store the image temporarily in local? I tried using addImage() but it is very hard to use, not only because I change the scale factor of pdf, but primarily because the content of the pdf is dynamic, and I do not know what size the images will have or their exact position.
You need to make sure the image(s) is/are loaded before addIMage(). The following code is what I used to convert multiple images online to a PDF file. It will rotate the image(s) based on the orientation of the images/page and set proper margin. Note that this code is for image only, not the Html page with embedded image(s), but the concept of img.onload remains the same.
As for image rotation, if you see a blank page after rotation, it could simply be that the image is out of bounds. See this answer for details.
function exportPdf(urls) {
let pdf = new jsPDF('l', 'mm', 'a4');
const pageWidth = pdf.internal.pageSize.getWidth();
const pageHeight = pdf.internal.pageSize.getHeight();
const pageRatio = pageWidth / pageHeight;
for (let i = 0; i < urls.length; i++) {
let img = new Image();
img.src = urls[i];
img.onload = function () {
const imgWidth = this.width;
const imgHeight = this.height;
const imgRatio = imgWidth / imgHeight;
if (i > 0) { pdf.addPage(); }
pdf.setPage(i + 1);
if (imgRatio >= 1) {
const wc = imgWidth / pageWidth;
if (imgRatio >= pageRatio) {
pdf.addImage(img, 'JPEG', 0, (pageHeight - imgHeight / wc) / 2, pageWidth, imgHeight / wc, null, 'NONE');
}
else {
const pi = pageRatio / imgRatio;
pdf.addImage(img, 'JPEG', (pageWidth - pageWidth / pi) / 2, 0, pageWidth / pi, (imgHeight / pi) / wc, null, 'NONE');
}
}
else {
const wc = imgWidth / pageHeight;
if (1 / imgRatio > pageRatio) {
const ip = (1 / imgRatio) / pageRatio;
const margin = (pageHeight - ((imgHeight / ip) / wc)) / 4;
pdf.addImage(img, 'JPEG', (pageWidth - (imgHeight / ip) / wc) / 2, -(((imgHeight / ip) / wc) + margin), pageHeight / ip, (imgHeight / ip) / wc, null, 'NONE', -90);
}
else {
pdf.addImage(img, 'JPEG', (pageWidth - imgHeight / wc) / 2, -(imgHeight / wc), pageHeight, imgHeight / wc, null, 'NONE', -90);
}
}
if (i == urls.length - 1) {
pdf.save('Photo.pdf');
}
}
}
}
If this is a bit hard to follow, you can also use .addPage([imgWidth, imgHeight]), which is more straightforward. The downside of this method is that the first page is fixed by new jsPDF(). See this answer for details. You can use window.open(pdf.output('bloburl')) to debug.
Is there a way to set a custom DPI/PPI when creating an image using the HTML5 canvas? I know how can I draw on the canvas and export it as an image, but how can I make sure the output image is of certain DPI/PPI. I guess using SVG elemnts to draw on the canvas is a way, but wouldn't that be flattened out when I export the whole canvas as an image? Or calculating the device DPI and then scaling the image to meet my DPI requirement, but that doesn't seem like the correct solution.
Canvases have two different 'sizes': their DOM width/height and their CSS width/height. You can increase a canvas' resolution by increasing the DOM size while keeping the CSS size fixed, and then using the .scale() method to scale all of your future draws to the new bigger size. Here's an example:
function changeResolution(canvas, scaleFactor) {
// Set up CSS size.
canvas.style.width = canvas.style.width || canvas.width + 'px';
canvas.style.height = canvas.style.height || canvas.height + 'px';
// Resize canvas and scale future draws.
canvas.width = Math.ceil(canvas.width * scaleFactor);
canvas.height = Math.ceil(canvas.height * scaleFactor);
var ctx = canvas.getContext('2d');
ctx.scale(scaleFactor, scaleFactor);
}
The canvas default resolution is 96dpi (CSS inches, not based on the actual screen). So a scaleFactor of 2 gives 192dpi, 3 is 288dpi, etc. In fact, here's a version that should give your desired DPI:
function setDPI(canvas, dpi) {
// Set up CSS size.
canvas.style.width = canvas.style.width || canvas.width + 'px';
canvas.style.height = canvas.style.height || canvas.height + 'px';
// Resize canvas and scale future draws.
var scaleFactor = dpi / 96;
canvas.width = Math.ceil(canvas.width * scaleFactor);
canvas.height = Math.ceil(canvas.height * scaleFactor);
var ctx = canvas.getContext('2d');
ctx.scale(scaleFactor, scaleFactor);
}
Have fun! Note that both these code samples can only be used once per canvas, they assume the current DOM size is the original (they could be tweaked to change that). Also the rescaling needs to happen before you do any drawing on the canvas. Thanks to this post for the method and information!
Edit: Here is a more robust function that will scale future draws and maintain existing canvas contents. This can be called to rescale multiple times.
function setDPI(canvas, dpi) {
// Set up CSS size.
canvas.style.width = canvas.style.width || canvas.width + 'px';
canvas.style.height = canvas.style.height || canvas.height + 'px';
// Get size information.
var scaleFactor = dpi / 96;
var width = parseFloat(canvas.style.width);
var height = parseFloat(canvas.style.height);
// Backup the canvas contents.
var oldScale = canvas.width / width;
var backupScale = scaleFactor / oldScale;
var backup = canvas.cloneNode(false);
backup.getContext('2d').drawImage(canvas, 0, 0);
// Resize the canvas.
var ctx = canvas.getContext('2d');
canvas.width = Math.ceil(width * scaleFactor);
canvas.height = Math.ceil(height * scaleFactor);
// Redraw the canvas image and scale future draws.
ctx.setTransform(backupScale, 0, 0, backupScale, 0, 0);
ctx.drawImage(backup, 0, 0);
ctx.setTransform(scaleFactor, 0, 0, scaleFactor, 0, 0);
}
You cannot (ugh) access the DPI of a display of the current web page in any browser:
Detecting the system DPI/PPI from JS/CSS?
For printing: You most likely cannot set the DPI of exported <canvas> image (PNG, JPEG) using browser standard functions. However, if you use a pure Javascript encoder image encoder you are free to create any sort of binary file you wish and manually adjust the DPI value embedded int he binary.
https://gist.github.com/1245476
If you just want to set the dpi of the PNG (ie not increase the number of pixels) then this library lets you set the pHYs chunk (amongst other things):
https://github.com/imaya/CanvasTool.PngEncoder
Minimal example to export an HTML5 canvas to base64-encoded PNG:
// convert dots per inch into dots per metre
var pixelsPerM = dpi * 100 / 2.54;
var param = {
bitDepth : 8,
colourType : 2,
filterType : 0,
height : canvas.height,
interlaceMethod : 0,
phys : {
unit : 1,
x : pixelsPerM,
y : pixelsPerM
},
width : canvas.width
};
var array = canvas.getContext('2d').getImageData(0, 0, canvas.width,
canvas.height).data;
var png = new window.CanvasTool.PngEncoder(array, param).convert();
var base64 = 'data:image/png;base64,' + btoa(png);
Use the library changedpi:
npm install changedpi --save
Also see
https://github.com/shutterstock/changeDPI
https://github.com/hongru/canvas2image
Example code that also allows to adapt the px size and resolution for png or jpg export:
Canvas2Image.saveAsImage('fileName.png', canvas, 2000, 3000, 300, 'png');
-
import Url from './url';
import * as ChangeDpi from 'changeDPI';
export default class Canvas2Image {
static saveAsImage(fileName, canvas, width, height, dpi, type) {
type = this._fixType(type);
canvas = this._scaleCanvas(canvas, width, height);
let dataUrl = canvas.toDataURL(type);
let dataUrlWithDpi = ChangeDpi.changeDpiDataUrl(dataUrl, dpi)
dataUrlWithDpi = dataUrlWithDpi.replace(type, 'image/octet-stream');
Url.download(fileName, dataUrlWithDpi);
}
static _fixType(type) {
type = type.toLowerCase().replace(/jpg/i, 'jpeg');
const r = type.match(/png|jpeg|bmp|gif/)[0];
return `image/${r}`;
}
static _scaleCanvas(canvas, width, height) {
const w = canvas.width;
const h = canvas.height;
if (width === undefined) {
width = w;
}
if (height === undefined) {
height = h;
}
const retCanvas = document.createElement('canvas');
const retCtx = retCanvas.getContext('2d');
retCanvas.width = width;
retCanvas.height = height;
retCtx.drawImage(canvas, 0, 0, w, h, 0, 0, width, height);
return retCanvas;
}
}
-
export default class Url {
static download(fileName, url) {
const element = document.createElement('a');
element.setAttribute('href', url);
element.setAttribute('download', fileName);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
static createUrlForBlob(blob) {
return this._URL.createObjectURL(blob);
}
static clearBlobUrl(blobUrl) {
this._URL.revokeObjectURL(blobUrl);
}
static get _URL() {
return window.URL || window.webkitURL || window;
}
}
I'm on Windows7 IE9 running in IE8. This works in IE9 only because I can use canvas however in IE8 it's suppose to fall back to flash canvas. Here is my source http://blog.jackadam.net/2010/alpha-jpegs/ NOW it seems im having a problem in IE with the context.drawImage not drawing the image? I've posted on the flashcanvas google group but they seem to take some time to repsond so was hoping there maybe a flashcanvas guru here.
;(function() {
var create_alpha_jpeg = function(img) {
var alpha_path = img.getAttribute('data-alpha-src')
if(!alpha_path) return
// Hide the original un-alpha'd
img.style.visiblity = 'hidden'
// Preload the un-alpha'd image
var image = document.createElement('img')
image.src = img.src + '?' + Math.random()
console.log(image.src);
image.onload = function () {
console.log('image.onload');
// Then preload alpha mask
var alpha = document.createElement('img')
alpha.src = alpha_path + '?' + Math.random()
alpha.onload = function () {
console.log('alpha.onload');
var canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
img.parentNode.replaceChild(canvas, img)
// For IE7/8
if(typeof FlashCanvas != 'undefined') FlashCanvas.initElement(canvas)
// Canvas compositing code
var context = canvas.getContext('2d')
context.clearRect(0, 0, image.width, image.height)
context.drawImage(image, 0, 0, image.width, image.height)
//context.globalCompositeOperation = 'xor'
//context.drawImage(alpha, 0, 0, image.width, image.height)
}
}
}
// Apply this technique to every image on the page once DOM is ready
// (I just placed it at the bottom of the page for brevity)
var imgs = document.getElementsByTagName('img')
for(var i = 0; i < imgs.length; i++)
create_alpha_jpeg(imgs[i])
})();
The solution to this was it only works with the older version of flashcanvas AND it only works with flashcanvas pro... as noted in the second footer of the website
This technique uses the globalCompositeOperation operation, which
requires FlashCanvas Pro. Free for non-profit use or just $31 for a
commercial license.
I got it working with flashcanvaspro. Depending which flash player it targets the max image size varies.
Flash Player 10 increased the maximum size of a bitmap to a maximum pixel count of 16,777,215.
Flash Player 9 limits (2880 x 2880 pixels).
https://helpx.adobe.com/flash-player/kb/size-limits-swf-bitmap-files.html
Need someone to update flashcanvas to the latest flash player