Adding text after image composite, html5 canvas - javascript

I have combined two images and some text using html5 canvas, but I can't seem to position the images the same way I can with the text. With the text I just changed the x and y properties to position it on the canvas, but this does not seem to work with my two images. They are just set at 0, 0 (top left) regardless.
<canvas width="850" height="450" id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img1 = loadImage('<%= image_url(#entry.picture(:small)) %>', main);
var img2 = loadImage("<%= image_url('overlay.png') %>", main);
var imagesLoaded = 0;
function main() {
imagesLoaded += 1;
if(imagesLoaded == 2) {
// composite now
ctx.drawImage(img1, 0, 0);
ctx.globalAlpha = 1;
ctx.drawImage(img2, 0, 0);
}
}
function loadImage(src, onload) {
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
ctx.font="30px sans-serif";
ctx.fillText("<%= full_name(#entry.user) %>", 60, 435);
ctx.fillStyle="#333333";
};
img.src = src;
return img;
}
</script>
In my head, the line ctx.drawImage(img1, 0, 0,); should position the image when the values of 0 and 0 are changed, but it does not. My Javascript knowledge isn't great, so there is probably something obvious, but I just can't figure it out. Any help would be greatly appreciated.
Thanks.

There are many styles of code used to preload images to insure they are fully loaded before you try to draw them using drawImage:
Here's annotated code and a Demo:
// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// put the paths to your images in imageURLs[]
var imageURLs=[];
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/multple/face1.png");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/multple/face2.png");
// the loaded images will be placed in imgs[]
var imgs=[];
var imagesOK=0;
startLoadingAllImages(imagesAreNowLoaded);
// Create a new Image() for each item in imageURLs[]
// When all images are loaded, run the callback (==imagesAreNowLoaded)
function startLoadingAllImages(callback){
// iterate through the imageURLs array and create new images for each
for (var i=0; i<imageURLs.length; i++) {
// create a new image an push it into the imgs[] array
var img = new Image();
imgs.push(img);
// when this image loads, call this img.onload
img.onload = function(){
// this img loaded, increment the image counter
imagesOK++;
// if we've loaded all images, call the callback
if (imagesOK>=imageURLs.length ) {
callback();
}
};
// notify if there's an error
img.onerror=function(){alert("image load failed");}
// set img properties
img.src = imageURLs[i];
}
}
// All the images are now loaded
// Do drawImage & fillText
function imagesAreNowLoaded(){
// the imgs[] array now holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
ctx.font="30px sans-serif";
ctx.fillStyle="#333333";
// drawImage the first image (face1.png) from imgs[0]
// and fillText its label below the image
ctx.drawImage(imgs[0],0,10);
ctx.fillText("face1.png", 0, 135);
// drawImage the first image (face2.png) from imgs[1]
// and fillText its label below the image
ctx.drawImage(imgs[1],200,10);
ctx.fillText("face2.png", 210, 135);
}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=350 height=300></canvas>

Related

Canvas image not drawing?

The code I'm using to load two images (note that one image is 7MB (I know - I will fix it later)).
var loaded = 0;
var img1 = new Image();
var img2 = new Image();
img1.onload = function(){ both() };
img2.onload = function(){ both() };
img1.src = 'map.png';
img2.src = 'ovl.png';
function both() {
loaded++
console.log(loaded);
if (loaded == 2) {
console.log("LOADED");
resizeCanvas();
console.log("RESIZED");
}
}
function resizeCanvas() {
//resize code
drawStuff();
}
function drawStuff() {
console.log("DRAWSTART");
ctx.save();
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle="#868f9c";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.restore();
ctx.drawImage(img1, 0,0);
ctx.drawImage(img2, 0,0);
console.log("DRAWED");
}
As expected the console output is;
(index):28 1
(index):28 2
(index):30 LOADED
(index):81 DRAWSTART
(index):90 DRAWEND
(index):64 RESIZED
But the images are nowhere to be found, most of the times. Sometimes they appear after ~30 seconds but then no other functions work (I have some panning/zooming stuff aswell).
Note that if I comment out one of the ctx.drawImage(img[1,2], 0,0); it works perfectly fine. It seems like drawing two images just isn't working...
You should test first with small images in order to check everything is ok. Then for managing big images, you can use a preload library like http://www.createjs.com/preloadjs

Resize HTML canvas with .scale()

I'm trying to resize a <canvas> with an image already drawn, but I'm misunderstanding how to use the canvas.scale() method because it doesn't shrink...
Code:
ImageRender.prototype.resizeTo = function () {
var canvas = $('#myCanvas')[0];
var ctx = canvas.getContext("2d");
//current image
var currImg = ctx.getImageData(0, 0, canvas.width, canvas.height);
//
var tempCanvas = $('canvas')[0];
var tempCtx = tempCanvas.getContext("2d");
tempCtx.putImageData(currImg, 0, 0)
//
ctx.scale(0.5, 0.5);
//redraw
ctx.drawImage(tempCanvas, 0, 0);
};
What am I overlooking?
Thanks!
You can scale your canvas with content by "bouncing" the content off a temporary canvas while you resize the original canvas. This save+redraw process is necessary because canvas content is automatically cleared when you resize the canvas width or height.
Example code:
var myCanvas=document.getElementById("canvas");
var ctx=myCanvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var tempCanvas=document.createElement("canvas");
var tctx=tempCanvas.getContext("2d");
var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/Dog-With-Cute-Cat.jpg";
function start(){
myCanvas.width=img.width;
myCanvas.height=img.height;
ctx.drawImage(img,0,0);
resizeTo(myCanvas,0.50);
}
function resizeTo(canvas,pct){
var cw=canvas.width;
var ch=canvas.height;
tempCanvas.width=cw;
tempCanvas.height=ch;
tctx.drawImage(canvas,0,0);
canvas.width*=pct;
canvas.height*=pct;
var ctx=canvas.getContext('2d');
ctx.drawImage(tempCanvas,0,0,cw,ch,0,0,cw*pct,ch*pct);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<h4>Canvas resized to 50%</h4>
<canvas id="canvas" width=300 height=300></canvas>
<h4>Img with original image</h4>
<img src='https://dl.dropboxusercontent.com/u/139992952/multple/Dog-With-Cute-Cat.jpg'>
Simpler way would be using the extra parameters of drawImage(). 4th and 5th parameters let you set the final width and height.
Also, you can paint an image (or a canvas) directly, without the need of getting the ImageData.
Also(2), I think you may want to resize the canvas too (just use its width and height properties)
https://jsfiddle.net/mezeL06o/

canvas overlay export

I have 2 canvas, canvas1 and canvas2. Both work well, but I want to mix them to export as image. Overlay css based do not work as it prints 2 images. Any point to start? thank you.
<canvas id="canvas1" style="position:relative; float:left;border:1px solid #000 " width="547" height="154">
</canvas>
<canvas id="canvas2" style="z-index: 1; position:absolute; float:left;" width="547" height="500">
</canvas>
Well, there are a few ways to go about this, and what do you mean by mix?
If you simply want to overlay canvas2 over canvas1, but don't want to alter either original canvas, you can send their data to another canvas, and then get that data.
method to follow:
draw canvas1 to canvas3
draw canvas2 to canvas3
get canvas3 image
working javascript:
// Make all the canvas and context variables */
var c1 = document.getElementById('c1');
var c2 = document.getElementById('c2');
var c3 = document.getElementById('c3');
var c4 = document.getElementById('c4');
var ctx1 = c1.getContext('2d');
var ctx2 = c2.getContext('2d');
var ctx3 = c3.getContext('2d');
var ctx4 = c4.getContext('2d');
/* */
// Draw square on canvas 1
ctx1.fillRect(0,0,50,50);
// Draw offset square on canvas 2
ctx2.fillRect(25,25,50,50);
// Make third image and onload function
var img3 = new Image();
img3.onload = function(){
// Draw this image to canvas 4 so that we know it worked
ctx4.drawImage(this,0,0);
}
// So we know when both have loaded
var imagesLoaded = 0;
function draw(){
// increment number loaded
imagesLoaded++;
// draw this image to canvas 3
ctx3.drawImage(this,0,0);
// if the have both loaded, then...
if (imagesLoaded == 2){
// set third image's src to the canvas 3 image
img3.src = c3.toDataURL();
}
}
// First image
var img1 = new Image();
// So it will draw on canvas 3
img1.onload = draw;
// Set the src to canvas 1's image
img1.src = c1.toDataURL();
// Second image
var img2 = new Image();
// So it will draw on canvas 3
img2.onload = draw;
// Set the src to canvas 2's image
img2.src = c2.toDataURL();
Working example here.
However, if that wasn't what you were looking for, I am sorry.

How do I handle many images in my HTML5 canvas?

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

How can i load an array of images in html5 canvas and swap one of the images on button click

i'm trying to build a bike configurator. This is my problem.
How can i load and array of images to construct the bike and another array with parts on the right from which when the user click i take the part and load it on the left where is the bike without preloading the entire canvas again. the new image will be the same width and height and should be on the same x/y position. This is how i load and array of images, but then i don't know how to swap them. I know that i can't clear the image that is loaded on the canvas and i have to draw the new one on top but i don't know how.
<script type="text/javascript" charset="utf-8">
function loadImages(sources, callback){
var images = {};
var loadedImages = 0;
var numImages = 0;
// get num of sources
for (var src in sources) {
numImages++;
}
for (var src in sources) {
images[src] = new Image();
images[src].onload = function(){
if (++loadedImages >= numImages) {
callback(images);
}
};
images[src].src = sources[src];
}
}
window.onload = function(images){
var canvas = document.getElementById("config");
var context = canvas.getContext("2d");
var sources = {
one: "one.jpg",
two: "two.jpg"
};
loadImages(sources, function(images){
context.drawImage(images.one, 100, 100, 180, 200);
context.drawImage(images.two, 280, 100, 180, 200);
});
};
</script>
How can i change image two.jpg on button click. The button should be outside the canvas.
button.addEventListener('click', function () {
canvas.width = canvas.width; // redraws canvas
sources.two = 'three.jpg';
// fyi, you are drawing the images as many times as there are sources.
loadImages(sources, function(images){
context.drawImage(images.one, 100, 100, 180, 200);
context.drawImage(images.two, 280, 100, 180, 200);
});
}, false);

Categories