I am trying to understand how I can utilize angular's $q library to display images which are based on a canvas drawing and then converted using .toDataURL();
Basically I want to:
Loop over a images ($scope.targetImages)
Draw them on a canvas
Convert them to images using .toDataURL() and store it in ($scope.outputImages);
Display the images using ng-repeat
The problem is, that the function .toDataURL() can take some time before executed, thus resulting in a delayed call of step 4, and thus nothing being displayed.
I have tried the following, but it still resolves before all the images are converted.
As I have it now, when I call drawCanvas() for the second time, then the images are shown.
// 1
$scope.targetImages= {}
drawCanvas().then(function(data){
console.log("done: " + new Date())
console.log(data)
$scope.outputImages = data;
$scope.previewMode = false; // switch views, display canvas, remove preview
});
function drawCanvas() {
var defer = $q.defer();
var targetImages = {}
angular.forEach($scope.targetImages , function(imageObj, key) {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = imageObj.nativeURL;
img.onload = start
// 2
function start() {
ctx.drawImage(img, 0, 0, img.width, img.height);
outputImages[key] = {
IID: key,
dataURL: canvas.toDataURL()
}
} // start
}); // for loop target images
defer.resolve(outputImages);
return defer.promise;
} // draw canvas
And displayed as:
<img ng-show="!previewMode" ng-src="{{image.dataURL || ''}}" style="width: 100vw; max-width: 600px;">
First, define a function that draws an image to the canvas and returns a promise for the result:
function drawToCanvas(nativeURL) {
return $q(function (resolve) {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = nativeURL;
img.onload = function () {
ctx.drawImage(img, 0, 0, img.width, img.height);
resolve(canvas.toDataURL());
};
});
}
The solution then becomes:
$scope.targetImages = [];
function drawCanvas() {
// pResults is an array of promises
var pResults = $scope.targetImages.map(function (imageObj) {
return drawToCanvas(imageObj.nativeURL);
});
return $q.all(pResults);
}
drawCanvas().then(function(data) {
// data is an array of imageUrls
console.log("done: " + new Date())
console.log(data)
$scope.outputImages = data;
$scope.previewMode = false;
// switch views, display canvas, remove preview
});
To simplify, I have changed $scope.targetImages and $scope.outputImages to be arrays instead of objects, but it shouldn't be too hard to go back to using objects for them if that's what you need.
Related
Im converting an SVG to a PNG and it's working fine except for some super bizarre behavior that setting the image src to the b64 value only works if you put it in a setTimeout of 0. If you copy the b64 value and hardcode it as the src it also works. Here's the JS:
var testSVG = {
height: 31.987199999999998,
template: '<svg width="19.2" height="31.987199999999998" viewBox="0 0 149.39 248.95" xmlns="http://www.w3.org/2000/svg"><path fill="#c599fe" stroke="#000" stroke-miterlimit="10" stroke-width="5" d="M74.89,236.14c-5.35-26.25-14.78-48.1-26.2-68.35-8.47-15-18.29-28.88-27.37-43.45-3-4.86-5.65-10-8.56-15C6.94,99.2,2.21,87.5,2.51,72.32A68.92,68.92,0,0,1,13.28,35.88,71.31,71.31,0,0,1,63.34,3.32,75.55,75.55,0,0,1,112,12.53a70.38,70.38,0,0,1,24,23.22,68.1,68.1,0,0,1,10.9,36.32A67.12,67.12,0,0,1,144,92.82c-1.8,6-4.69,11-7.26,16.34-5,10.44-11.32,20-17.64,29.57C100.29,167.24,82.62,196.3,74.89,236.14Z"/><circle cx="74.69" cy="72.16" r="25.29"/></svg>',
width: 19.2
}
// Pass in the testSVG object
var convertSVGtoBitmap = function (svgObject) {
if(!svgObject) return null;
var canvas = document.createElement("canvas");
canvas.width = Math.ceil(svgObject.width);
canvas.height = Math.ceil(svgObject.height);
var ctx = canvas.getContext("2d");
// Convert the SVG string into a base64 and append a header
var svg = btoa(svgObject.template);
var b64Start = 'data:image/svg+xml;base64,';
var image64 = b64Start + svg;
// Draw the SVG onto the canvas instance
var img = new Image();
img.src = image64;
ctx.drawImage(img, 0, 0);
// Return both svg base64 and png base64
return {svg: image64, png: canvas.toDataURL()};
};
console.warn('test')
// Get SVG base64 stuff
var svgimg = document.createElement("img");
document.getElementById('svg-render').appendChild(svgimg);
svgimg.src = convertSVGtoBitmap(testSVG).svg;
// Get converted PNG base64 stuff
var pngimg = document.createElement("img");
document.getElementById('png-render').appendChild(pngimg);
setTimeout(function () {
pngimg.src = convertSVGtoBitmap(testSVG).png;
}, 0)
Note, this works because of the setTimeout of 0. If I change it to just pngimg.src = convertSVGtoBitmap(testSVG).png; without the setTimeout it doesn't display. If I do pngimg.src = '...' where the ... is the hardcoded b64 value it also works. Here's a JSBin if you want to mess with it.
https://jsbin.com/qecedev/2/edit?html,js,output
I also tried putting it in a document.ready from jQuery as well as adding an onload to the pngimg object and adding the src in that.
I figured it out. The problem area was this
// Draw the SVG onto the canvas instance
var img = new Image();
img.src = image64;
ctx.drawImage(img, 0, 0);
// Return both svg base64 and png base64
return {svg: image64, png: canvas.toDataURL()};
The png value in the return wasnt loaded yet. I converted it to have a callback (you could use async or promises too) and it started working.
// USE CALLBACK
var convertSVGtoBitmap = function (svgObject, callback) {
if(!svgObject) return null;
var canvas = document.createElement("canvas");
canvas.width = Math.ceil(svgObject.width);
canvas.height = Math.ceil(svgObject.height);
var ctx = canvas.getContext("2d");
var svg = btoa(svgObject.template);
var b64Start = 'data:image/svg+xml;base64,';
var image64 = b64Start + svg;
var img = new Image();
// WAIT FOR IMAGE TO LOAD
img.onload = function () {
ctx.drawImage(img, 0, 0);
// NOW WE CAN RETURN VALUES!
callback(image64, canvas.toDataURL());
}
img.src = image64;
};
I am relatively new to JavaScript. The concept of callbacks is confusing me a bit coming from an OOP background
I am trying to create a hidden canvas for an image object and then get its pixel data.
I have an ImageObject on which I would eventually want to store all the properties like image, pixels and so on.. Inside start() , first I get references to maincanvas and mainctx. Then I load the image and once the image is drawn, I store its pixel data in ImageObject.pixels
However inside the start(), the code runs asynchronously and the log statement to display ImageObject.pixels return null
How do I use callbacks to solve this?
Below is my code
ImageObject = {};
var MainCtx;
var MainCanvas;
//get the image pixel properties
function start()
{
MainCanvas = document.getElementById("canvas");
MainCtx = MainCanvas.getContext('2d');
ImageObject.image = loadImage();
console.log(" Image pixels " +ImageObject.pixels); // -> displays NULL because code runs asynchronously, how do I use callback here to avoid this?
}
function loadImage()
{
var image = new Image();
image.src = 'image.jpg';
image.addEventListener('load',function()
{
MainCtx.drawImage(image,MainCanvas.width/2,MainCanvas.height/2);
console.log("width here" +image.width+ " maincanvas " +MainCanvas+ " mainctx " +MainCtx+ " image " +image);
ImageObject.pixels = getImagePixels(image); //-> store pixel data in the image
});
return image;
}
function getImagePixels(img)
{
var c = getCanvas(img.width,img.height);
var ctx = c.getContext('2d');
return ctx.getImageData(0,0,c.width,c.height);
}
function getCanvas(w,h)
{
var c = document.createElement('canvas');
c.width = w;
c.height = h;
return c;
}
start();
simple add new function that will be called when all process is finished.
change
function start()
{
MainCanvas = document.getElementById("canvas");
MainCtx = MainCanvas.getContext('2d');
ImageObject.image = loadImage();
console.log(" Image pixels " +ImageObject.pixels); // -> displays NULL because code runs asynchronously, how do I use callback here to avoid this?
}
to
function start()
{
MainCanvas = document.getElementById("canvas");
MainCtx = MainCanvas.getContext('2d');
ImageObject.image = loadImage();
}
and change
function loadImage()
{
var image = new Image();
image.src = 'image.jpg';
image.addEventListener('load',function()
{
MainCtx.drawImage(image,MainCanvas.width/2,MainCanvas.height/2);
console.log("width here" +image.width+ " maincanvas " +MainCanvas+ " mainctx " +MainCtx+ " image " +image);
ImageObject.pixels = getImagePixels(image); //-> store pixel data in the image
});
return image;
}
to
function loadImage()
{
var image = new Image();
image.src = 'image.jpg';
image.addEventListener('load',function()
{
MainCtx.drawImage(image,MainCanvas.width/2,MainCanvas.height/2);
console.log("width here" +image.width+ " maincanvas " +MainCanvas+ " mainctx " +MainCtx+ " image " +image);
ImageObject.pixels = getImagePixels(image); //-> store pixel data in the image
done();
});
return image;
}
and add this
function done()
{
console.log(" Image pixels " +ImageObject.pixels); // -> displays NULL because code runs asynchronously, how do I use callback here to avoid this?
}
I'm trying to add images to canvas strictly, but images are added randomly.
What's the problem?
Here is my simple code.
var canvas = new fabric.Canvas("preview");
var imgs = ['bgBottom','bgTop', 'bgLevel', 'bgCircle'];
for (var i=0; i<imgs.length;i++){
var url = imgs[i]+'.png';
fabric.Image.fromURL(url, function (oImg) {
canvas.add(oImg)
})
}
fabric.Image.fromURL loads the image in the background and runs the anonymous function you pass to it once image load is complete which adds it to the canvas. The order that the browser loads the images will vary and you can't rely on it being in a specific order.
Check out this jsfiddle that shows loading an array of images and making sure they're displayed in a set order. This works by adding the image to the canvas before it's loaded; it just doesn't render until the image is available to be displayed.
The code from the jsfiddle:
var SelfLoadingImage = fabric.util.createClass(fabric.Object, {
initialize: function(src) {
this.image = new Image();
this.image.src = src;
this.image.onload = (function() {
this.width = this.image.width;
this.height = this.image.height;
this.loaded = true;
this.setCoords();
this.fire('image:loaded');
canvas.renderAll();
}).bind(this);
},
_render: function(ctx)
{
if (this.loaded) {
ctx.drawImage(this.image, -this.width / 2, -this.height / 2);
}
}
});
var canvas = new fabric.Canvas("preview");
var imgs = [
'http://icons.iconarchive.com/icons/fasticon/ifunny/128/dog-icon.png', // dog
'http://33.media.tumblr.com/avatar_14ee6ada72a4_128.png', // cat
'http://upload.wikimedia.org/wikipedia/commons/b/bc/Nuvola_devices_mouse.png' // mouse
];
for (var i=0; i<imgs.length;i++){
var url = imgs[i];
var img = new SelfLoadingImage(url);
canvas.add(img);
}
I'm very new to Html5 canvas and Javascript. I'm trying this :
function animate() {
var image1 = new Image();
image.src = /path
var image2 = new Image();
image2.src = /path
for(;;)
{
//change value of x and y so that it looks like moving
context.beginPath();
context.drawImage(<image>, x, y );
context.closePath();
context.fill();
}
}
EDIT:
And I call the animate function each 33ms :
if (playAnimation) {
// Run the animation loop again in 33 milliseconds
setTimeout(animate, 33);
};
If I follow the answer given here, I get the image struck and its not moving any further.
Update: Based on new information in the question, your problem (restated) is that you want to either
wait for all images to load first, and then start animating with them, or
start animating and only use an image if it is available.
Both are described below.
1. Loading many images and proceeding only when they are finished
With this technique we load all images immediately and when the last has loaded we run a custom callback.
Demo: http://jsfiddle.net/3MPrT/1/
// Load images and run the whenLoaded callback when all have loaded;
// The callback is passed an array of loaded Image objects.
function loadImages(paths,whenLoaded){
var imgs=[];
paths.forEach(function(path){
var img = new Image;
img.onload = function(){
imgs.push(img);
if (imgs.length==paths.length) whenLoaded(imgs);
}
img.src = path;
});
}
var imagePaths = [...]; // array of strings
loadImages(imagePaths,function(loadedImages){
setInterval(function(){ animateInCircle(loadedImages) }, 30);
});
2. Keeping track of all images loaded so far
With this technique we start animating immediately, but only draw images once they are loaded. Our circle dynamically changes dimension based on how many images are loaded so far.
Demo: http://jsfiddle.net/3MPrT/2/
var imagePaths = [...]; // array of strings
var loadedImages = []; // array of Image objects loaded so far
imagePaths.forEach(function(path){
// When an image has loaded, add it to the array of loaded images
var img = new Image;
img.onload = function(){ loadedImages.push(img); }
img.src = path;
});
setInterval(function(){
// Only animate the images loaded so far
animateInCircle(loadedImages);
}, 100);
And, if you wanted the images to rotate in a circle instead of just move in a circle:
Rotating images: http://jsfiddle.net/3MPrT/7/
ctx.save();
ctx.translate(cx,cy); // Center of circle
ctx.rotate( (angleOffset+(new Date)/3000) % Math.TAU );
ctx.translate(radius-img.width/2,-img.height/2);
ctx.drawImage(img,0,0);
ctx.restore();
Original answer follows.
In general, you must wait for each image loading to complete:
function animate(){
var img1 = new Image;
img1.onload = function(){
context.drawImage(img1,x1,y1);
};
img1.src = "/path";
var img2 = new Image;
img2.onload = function(){
context.drawImage(img2,x2,y2);
};
img2.src = "/path";
}
You may want to make this code more DRY by using an object:
var imgLocs = {
"/path1" : { x:17, y:42 },
"/path2" : { x:99, y:131 },
// as many as you want
};
function animate(){
for (var path in imgLocs){
(function(imgPath){
var xy = imgLocs[imgPath];
var img = new Image;
img.onload = function(){
context.drawImage( img, xy.x, xy.y );
}
img.src = imgPath;
})(path);
}
}
I'm just learning JS, trying to do things without jQuery, and I want to make something similar to this however I want to use an array of images instead of just the one.
My image array is formed like this
var image_array = new Array()
image_array[0] = "image1.jpg"
image_array[1] = "image2.jpg"
And the canvas element is written like this. (Pretty much entirely taken from the Mozilla site)
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.src = 'sample.png';
img.onload = function(){
for (i=0;i<5;i++){
for (j=0;j<9;j++){
ctx.drawImage(img,j*126,i*126,126,126);
}
}
}
}
It uses the image "sample.png" in that code but I want to change it to display an image from the array. Displaying a different one each time it loops.
Apoligies if I've not explained this well.
Just iterate over the array, and position the images by using its width and height properties:
function draw() {
var ctx = document.getElementById('canvas').getContext('2d'),
img, i, image_array = [];
image_array.push("http://sstatic.net/so/img/logo.png");
image_array.push("http://www.google.com/intl/en_ALL/images/logo.gif");
// ...
for (i = 0; i < image_array.length; i++) {
img = new Image();
img.src = image_array[i];
img.onload = (function(img, i){ // temporary closure to store loop
return function () { // variables reference
ctx.drawImage(img,i*img.width,i*img.height);
}
})(img, i);
}
}
Check this example.