How do I know when HTML5 Canvas' Rendering is Finished? [duplicate] - javascript

This question already has answers here:
HTML5 Canvas: Get Event when drawing is finished
(5 answers)
Closed 1 year ago.
html:
<canvas id="cnv" width="786" height="1113">
js:
var img = new Image(),
cnv = document.getElementById('cnv');
var context = cnv.getContext('2d');
img.onload = function () {
context.drawImage(img, 0, 0, 786, 1113);
alert('finished drawing');
}
img.src = 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white_fe6da1ec.png';
http://jsfiddle.net/FxrSa/14/
I want to show the alert after the canvas finished his rendering. But the alert show before the image is drawn.
How can I wait for the GUI thread to finish his rendering?

Canvas drawImage is synchronous. And even, really synchronous.
Your problem is that alert() is blocking, and even really blocking.
By this I mean it does not only block the js execution, it also blocks the page rendering. So the browser has painted your image on your canvas, but didn't display it yet when you called alert().
One should always avoid alert and replace it with normal DOM elements.
Ps: Here is a proof that your image is indeed already painted on the canvas.

Double buffered canvas
An on screen canvas has two pixel buffers. One is called the back buffer, all rendering is done directly to the back buffer. When you make a render call, ctx.drawImage(foo,0,0); the function will not return until it has drawn the back buffer pixels. Even if the GPU is doing the rendering and the CPU is doing nothing, Javascript will wait until the rendering is complete befor moving on to the next line.
When the canvas is on the screen, you will not see the results of any rendering until the current execution has finished.
function myRender(){
ctx.draw(foo,0,0); // draw stuff
... new pixel content is only in back buffer
return;
}
function myLoop(){
ctx.clearRect(,0,0,w,h);
myRender(); // draw stuff
.. new pixels not visible
}
myLoop();
// no more code
When the myLoop function has returned and javascript has nothing to do, the DOM will see that the canvas backbuffer has changed. It then moves the back buffer to the front buffer so that it can be seen by the hardware that creates the display signal.
This is called double buffering, and it stop artifacts like shearing and flickering caused when you draw to the screen and the screen displays part of the rendering before it is finished.
When the canvas is offscreen, there is no front buffer.
The same is true for all DOM content.

As a workaround you may try this:
//after the rendering
setTimeout(function(){
alert("Yay");
},100);
HTML5 Canvas: Get Event when drawing is finished

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);
}
}

Prevent html5 Canvas from clearing when window is blurred. (requestAnimationFrame)

I made a simple canvas animation using a function which clears and redraws the canvas, and the calling requestAnimationFrame, It works awesome but when the window is blurred for long, say 10 secs, then the canvas clears itself and nothing's drawn. May anybody give an Idea why it's happening and how to solve it?
The structure of function is like :-
function drawFrame(time){
//clear and redraw to be understood as working functions in prototype ...
canvas.clear();
canvas.redraw();
requestAnimationFrame(drawFrame);
}
requestAnimationFrame(drawFrame);

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)
);

Is it possible to use getDataImage on a canvas that has undergone transformation in HTML?

I am trying to grab a particular part of the canvas and then put that image back onto the canvas in a very particular way. However, it seems that the get and put ImageData methods work on an absolute canvas that is not affected by image manipulations. Is there any way to use translations with the get and put dataImage operations in HTML5?
I have a line drawing that occurs at an angle and I want to capture that image, put it on its own canvas, do some processing on it, and then put it back on the canvas at that exact angle and position. I originally thought I could do this by repositioning the canvas based on the position and angle of the drawing, but this did not work because get and put dataImage use absolute rather than relative coordinates.
You could send the data to an image, and draw the image to the new canvas for processing. That way, you will get what appears on the canvas, exactly as it appears.
var img = new Image();
img.onload = function(){
processingCanvas.width = this.width;
processingCanvas.height = this.height;
processingCanvas.drawImage(this,0,0);
}
img.src = originalCanvas.toDataURL();
And boom, it's on your processing canvas (after you wait for it some). As long as you don't have an absolutely HUGE canvas, this method should work rather quickly. Just get everything you want, and make sure it is visible on the canvas. And then you know how to get the processed data back to the other canvas. I hope this was what you were looking for.

Image readystate in canvas

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

Categories