Image on HTML5 canvas only appearing for one frame - javascript

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

Related

createjs removed all existing info on canvas?

I am trying to verify that this happens no matter what, and there's no way to bypass it. It seems pretty silly to me that createjs uses this architecture. But I noticed that creating a stage from an existing canvas element removes all shapes, writings, etc from the canvas? Code is below:
html:
<canvas id="canvas" width="800" height="400"></canvas>
js:
var canv = document.getElementById("canvas");
var stage = new createjs.Stage(canv);
var ctx = canv.getContext('2d');
ctx.beginPath();
ctx.arc(50,50,10,0,2*Math.PI);
ctx.stroke();
createjs.Ticker.addEventListener("tick", tick);//circle created is overwritten here!!!?! Why createjs!?
//stage.update();
createjs.MotionGuidePlugin.install();
var shape1 = new createjs.Shape();
shape1.graphics.f("#000000").dc(0,0,10);
var path1 = new createjs.Shape();
path1.graphics.beginStroke("#ff0000").mt(0,0).qt(50,100,100,0);
stage.addChild(path1, shape1);
createjs.Tween.get(shape1).to({guide:{ path:[0,0, 50,100, 100,0] }},2000, createjs.Ease.cubicInOut);
function tick(event) {
stage.update();
}
Is this something that cannot be bypassed? It seems silly to me that createjs wouldn't just actually use the existing element unerased. If not, what is the point in passing in an element in the first place, why doesn't it just create a canvas element, and give you the ID? Anyways, if this is how it's going to be, unfortunately, I am going to have to go somewhere else. Sad, because createjs seemed pretty useful.
CreateJS uses a retained graphics mode, that is, it stores the state and redraws it each time. This is because the canvas is basically a big Bitmap with drawing commands – clearing the stage is the only way to remove the previous state.
But good news! There are lots of ways to get around these limitations if you want to blend CreateJS content with other content, or even make additive drawing effects.
The first is easy, which is setting autoClear. This will prevent the clear, and just draw the new contents over the old one.
stage.autoClear = false;
The second is a bit tougher, but great for instances where you want to mix CreateJS content with other libraries or effects. You can basically use the other canvas as the source to a Bitmap you include in CreateJS:
// Create a child for CreateJS referencing the other canvas
var bmp = new createjs.Bitmap(otherCanvas);
// Add it at the bottom (or top or wherever) in your new CreateJS canvas
stage.addChildAt(bmp, 0);
This is a great approach because it lets you put your content wherever you want, edit it separately, etc.
If you have a different case this doesn't cover, let me know and I can try to make a recommendation!
Cheers.

Using globalCompositeOperation for a limited number of images

I have a very simple question : is it possible to use globalCompositeOperation for only a restricted number of images?
For example, I draw a lot of stuff into my canvas. And on top of everything, and completed unrelated, I want to do some operations on two images (and I just want the result to be displayed, not both images). How can that be done?
For now, doing such operations affects everything that's already drawn underneath.
So a solution I found is doing the operations in another canvas, which I display on top of my main, first canvas. But this looks bad. First, it hits performances. Then, it doesn't feel intuitive. And last, I loose control over the layers : whatever is in my second canvas will always be on top of the first canvas.
This looks like a pretty simple feature, I hope I'm just bad at googling!
Thanks a lot!
Create a offscreen canvas and use it as a work space. You can create many as long as you have the RAM to store them.
To create an offscreen canvas
function createCanvas(w,h){
var canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
canvas.ctx = ctx.getContext("2d");
return canvas;
}
Easy as that and then you just treat it as an image. To draw to another canvas
var offScreenCan = createCanvas(1024,1024);
offScreenCan.ctx.drawImage(myImage); // put something on the canvas
ctx.drawImage(offScreenCan,0,0); // draw that canvas to another
I attach the context to the canvas rather than wrap the canvas in a containing object. I used to worry that the canvas would affect performance now I convert all images to canvas as soon as I load them and it does not impact performance at all.

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

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.

Javascript Loading Image

I've created a html5 web app to display data, and to mimmic swipe gestures I've used A Jquery plugin Called Wipetouch. When a wipe gesture is triggered, all I do is redraw all of my data with new numbers via a javascript function. I've realized that this isn't the optimal solution as the images are static, and are currently being loaded every time I swipe. Any ideas would be great.
edit
var img01 = new Image();
enter code here
img01.onload = function () {
ctx.drawImage(img01, x, y, img01.width * 2, img01.height * 2);
ctx.fillStyle = "white";
//draw text
ctx.font = "bold 28pt Calibri";
ctx.fillText(monthname[date.getMonth()], x+51, y+135);
ctx.fillText(d[1], x+47, y+37);
}
img01.src = 'images/retail_car.png';
I apologize for not making this clear earlier. I'm drawing the images on my canvas, and this code is triggered each time the wipetouch plugin registers a swipe. I'd like to make everything stay in the canvas, so the CSS fix that was mentioned won't work in my case.
You could put the images in your html and give them a class in css that has display:none;. Then when you call the function you could change the class of the displayed image to one with display: block; or however you need them displayed. Just be sure to change the class back after you swipe so that the new image appears and the old image is no longer visible. That way they are not being generated over again each time you call the swipe.

Categories