Image readystate in canvas - javascript

Is it possible to use imagename.readyState in canvas?
If not does anyone know a way of detecting when an image being drawn to the canvas using "drawImage" has loaded and is ready to display?
I am creating an image showcase using the canvas - when an image is selected I want to have a loading animation (which I have already created) display until the loaded condition is met.
I am still learning to use javascript and have been trying all day to no avail - so apologies for the lack of example code to display and illustrate what I'm asking!

You might try loading the image by using new Image() and setting the .onload event to draw the image on the canvas after the image has been loaded.
var img = new Image();
img.onload = function() {
// code to draw image on the canvas...
}
img.src = "/path/to/img.jpg";
See also: https://developer.mozilla.org/samples/canvas-tutorial/3_1_canvas_drawimage.html

Related

Image on HTML5 canvas only appearing for one frame

Long time lurker but never made an account. Just wanted to preface that I'm by no means a dev and just tinkering and experimenting for fun, so I apologise in advance if I seem really dumb.
I'm working on a dynamic overlay for Twitch streaming and was previously using AS3 but I've switched over to HTML5 now. I'm trying to load an image onto the canvas (which will eventually be a profile picture fetched using Twitch API... but one step at a time). I'm using Adobe Animate and I have the following so far applied in Actions on the first frame of the layer:
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
show_image();
function show_image() {
source_image = new Image();
source_image.src = 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png';
source_image.onload = function () {
context.drawImage(source_image, 100, 100);
}
}
When I hit Ctrl+Enter and see it in Chrome, the image appears for the first frame then disappears. I'm not sure how I'm supposed to get it to stay indefinitely. I need to be able to animate it later, and it'll change depending on the latest follow/donation/sub, etc.
I tried extending the frame itself in the timeline, however, this just changed long how it took to loop and didn't make the image itself stay longer. I'm probably missing something really simple!
Any help would be appreciated. Thanks!
Your code is okay if your approach is using a canvas with HTML and JS, without any libraries involved. However, this is not the case, as you are using Animate, and the way to draw graphics with it is different than using default canvas methods like drawImage().
Animate includes the CreateJS suite, which includes the EaselJS library ,and this allows you to use another tools to draw to your canvas. Two or them are the Stage object, the visual container of your animate project, and the Bitmap object, who represents an image, canvas or video. For effects of this question, only both objects are required.
Note that the code below is only for the first frame:
/* It is not necessary to declare the canvas or stage element,
as both are already declared. At this point the stage is ready to be drawn */
show_image();
function show_image() {
var source_image = new Image();
source_image.src = 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png';
source_image.onload = function(event) {
/* A new Bitmap object is created using your image element */
var bmp = new createjs.Bitmap(event.currentTarget);
/* The Bitmap is added to the stage */
stage.addChild(bmp);
}
}

Fabric.js background appears only after click

With the following code I create a Fabric canvas
canvas = new fabric.Canvas('canvas');
canvas.setWidth(660);
canvas.setHeight(590);
fabric.Image.fromURL('assets/img/materials/marble.bmp', function(image) {
image.set({
// I need this because the image size and the canvas size could be different
// in this way the image always covers the canvas
width:660,
height:590
});
canvas.setBackgroundImage(image);
});
canvas.renderAll();
The canvas is created, but the background image doesn't appear unless I click inside the canvas, as I click inside the canvas the background appears.
I'm working on my local machine and the application will not be published online.
Why do you think that I'm having this problem? Am I doing anything wrong? How could I fix this behaviour?
fabric.image.fromURL is asyncronous.
You have to call the renderAll() inside the callback if you want to show the backgroundimage asap.
Otherwise your mouse click will trigger a renderAll some fraction of second after the load is finished and the background will be rendered.
canvas = new fabric.Canvas('canvas');
canvas.setWidth(660);
canvas.setHeight(590);
fabric.Image.fromURL('assets/img/materials/marble.bmp', function(image) {
image.set({
// I need this because the image size and the canvas size could be different
// in this way the image always covers the canvas
width:660,
height:590
});
canvas.setBackgroundImage(image);
canvas.renderAll();
});
In my case, Safari iOS would not render the background ~20-60% of the time (version "fabric": "^4.3.1"). Waiting did not resolve. Tapping the canvas would activate/render the background. Adding renderAll() in various places did not resolve it for me. Did not happen on Chrome, only Safari iOS (ver. 14.1 at the time)
B64 workaround:
Dropping the fabric.Image.fromURL and instead providing a b64 image to setBackgroundImage worked for me consistently with all browsers.
let myImg = `data:image/jpeg;charset=utf-8;base64,<- base64 data->`
this.canvasObj.setBackgroundImage(
myImg, //b64
this.canvasObj.renderAll.bind(this.canvasObj)
);

Making images draggable to HTML5 Canvas, moving images out of canvas

I'm trying to make a custom avatar maker, where my users can drag & drop images to the position they want (clothes etc. I take the image urls from database based on what they own). Then they can save the look as png image to my site (using php). I have no experience on javascript/jquery but I don't think that this can be without them. So I've found amazing code for this from here:
http://www.fabiobiondi.com/blog/2012/10/export-and-save-a-screenshot-of-an-html5-canvas-using-php-jquery-and-easeljs/
But the images are already in the canvas and can't go outside of it, which is bad considering that someone could have 100 pieces of clothing and didn't want to display them all. Also I have to make custom code for each piece, which is also bad because not all users have the same images to drag.
Is there a way to put all images draggable (to the canvas), so I could easily add the image urls from my database as basic html/css? Is it possible that the images would be outside of the canvas first? Or should I create another canvas for the items users don't want?
the script in the article uses a static image because its goal is only explain how to export a canvas to bitmap : )
I have written another small article where I describe how to upload N images from your hard drive into a canvas ( using CreateJS ) so as you can see the process to load dynamic sources is not so hard.
http://www.fabiobiondi.com/blog/2012/10/upload-images-from-the-user-hard-driveto-an-html5-canvas-easel-js-application/
Anyway, if you need to load an image into a canvas you can simply use a syntax like this:
var img = new createjs.Bitmap('http://uri/image.jpg')
img.x = 50;
img.y = 50;
stage.addChild(img)
stage.update();
and if you need to know when an image is completely loaded you should listen for the onload event:
var image = new Image();
image.onload = onImageLoaded;
image.src = "http://uri/image.jpg";
function onImageLoaded (event) {
var img = new createjs.Bitmap(event.target)
img.x = 50;
img.y = 50;
stage.addChild(img)
stage.update();
}
hope it's useful

Switching JS canvas element with another element

I'm working with a modified face-to-gif - the prototype can be found here: http://bookfeels.herokuapp.com/. Basically, it's an app that uses your webcam to make a GIF.
I'm trying to simplify the UI, so I want the canvas that's recording to fade out and be replaced by the generated GIF, then fade back in again if the user wants to re-record. The two elements I'm working with are here:
facetogif.canvas = document.createElement('canvas');
facetogif.gifContainer = document.getElementById('gifs-go-here');
So, I want the facetogif.canvas to fade out, and be replaced by the facetogif.gifContainer, but I'm new to JS and I'm not sure how to search for this. Can anyone point me in the right direction? Thanks in advance!
No problem.
Here's how to change an image on the canvas:
function imgChange(imagePath) {
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
};
img.src=imagePath;
}
You mentioned also that you want to fade out an image as well. I'd say the easiest way to do that is with jQuery's fadeOut method.
It might seem a little intimidating, but it honestly isn't much different that from what you're already doing with document.createElement and such.

Is it possible to draw multiple SVG's to a canvas?

Background
I've got a bunch of svg's in a document (with rect, path, and whatnot inside each) and I need to draw this out to a downloadable PNG image. I understand that in order to do this there are two methods: either draw the page's HTML structure to a canvas and then export from there or render an SVG and its contents straight onto a canvas.
Hypotheses
The first hypothesis I tried to render the HTML structure using html2canvas and only found out that SVG's could not be rendered via an HTML structure at all (due to security issues). The second hypothesis I tried to render an SVG to canvas via canvg only to find out that it only allowed for one SVG element to be rendered and that only the first one would be rendered.
Results
To prove the first one wrong, type in http://www.w3schools.com/svg/tryit.asp?filename=trysvg_rect to this URL and disable Javascript. To prove the second one wrong I have a fiddle to try out.
The Question
I want to make it clear that my reasoning for having multiple svg's is so that I can place them within a responsive grid system and resize via aspect ratio. Without further ado, I ask my question: How can you render multiple svg elements to a canvas? If the answer to that question is "it isn't possible", then next my question would be: Should I be rendering one svg instead and handle responsiveness another way?
You should be able to draw SVG to canvas just as any other image:
var img1 = document.createElement('img'),
img2 = document.createElement('img')
count = 2;
/// image loading is async, make sure they are loaded
img1.onload = img2.onload = function() {
count--;
if (count === 0) drawImages();
}
img1.src = 'some1.svg';
img2.src = 'some2.svg';
/// when loaded, draw them somewhere on the canvas
function drawImages() {
ctx.drawImage(img1, 0, 0);
ctx.drawImage(img2, someX, someY);
}
That being said - there are a couple of restrictions:
FireFox currently does not want to draw images properly without width and height set inside the SVG file.
CORS (Cross-Origin Resource Sharing) applies if you want to extract images as bitmap (toDataURL/getImageData). If not they should work as normal.

Categories