How to overlay an image in HTML 5 canvas - javascript

Basically I have two images that i need to display at the same time(and more later).
var Canvas = function(canvasEl, width, height){
this.el= canvasEl;
this.el.width = width;
this.el.height = height;
this.ctx = canvasEl.getContext("2d");
}
var canvas = new Canvas(document.querySelector("#mycanvas"), 1100, 650);
var add = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 500,-215);
};
add.src="add.png";
var currentdate = new Date();
var datetime = currentdate.getHours();
if(datetime==1||datetime==13){
var clock1 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock1.png";
}
else if(datetime==2||datetime==14){
var clock2 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock2.png";
}
else if(datetime==3||datetime==15){
var clock3 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock3.png";
}
else if(datetime==4||datetime==16){
var clock4 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock4.png";
}
else if(datetime==5||datetime==17){
var clock5 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock5.png";
}
else if(datetime==6||datetime==18){
var clock6 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock6.png";
}
else if(datetime==7||datetime==19){
var clock7 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock7.png";
}
else if(datetime==8||datetime==20){
var clock8 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock8.png";
}
else if(datetime==9||datetime==21){
var clock9 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock9.png";
}
else if(datetime==10||datetime==22){
var clock10 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 600,100);
};
add.src="clock/clock10.png";
}
else if(datetime==11||datetime==23){
var clock11 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock11.png";
}
else if(datetime==12||datetime==0){
var clock12 = new Image();
add.onload = function() {
canvas.ctx.drawImage(this, 0,0);
};
add.src="clock/clock12.png";
}
</script>
</body>
I have that currently and all it is supposed to do is have one image named "add.png" and another (based on the time) called "clock.png" to display at the same time in different locations on the canvas. The code works but it only shows the clock.

You need a separate .onload for each image--not just 1 add.onload
// not always add.onload ...
add.onload ... add.src="add.png";
clock1.onload ... clock1.src="clock/clock1.png";
clock2.onload ... clock2.src="clock/clock2.png";
// same for clock3-12
Keep in mind that images are loaded asynchronously, so the load order of your images is not guaranteed to be the same as your code. That may or may not be a problem depending on how the images fit together.
Here's an example of an image loader that guarantees all images are loaded and that the images are all in your specified order:
// image loader
var imageURLs=[];
var imagesOK=0;
var imgs=[];
imageURLs.push("add.png");
imageURLs.push("clock/clock1.png");
imageURLs.push("clock/clock2.png");
imageURLs.push("clock/clock3.png");
imageURLs.push("clock/clock4.png");
imageURLs.push("clock/clock5.png");
imageURLs.push("clock/clock6.png");
imageURLs.push("clock/clock7.png");
imageURLs.push("clock/clock8.png");
imageURLs.push("clock/clock9.png");
imageURLs.push("clock/clock10.png");
imageURLs.push("clock/clock11.png");
imageURLs.push("clock/clock12.png");
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
// the imgs[] array holds your fully loaded images
// the imgs[] are in the same order as imageURLs[]
}

Related

Use p5js script for an NFT?

I have seen people use this method for SVG-based NFTs:
function p5jsToImageURI(){
string memory baseURL = "data:image/svg+xml;base64,PUT-BASE64-HERE"
}
But, since I don't want to generate a fixed image how can I use my p5js script (that looks slightly different each time the js code runs)? Is there a way to just somehow pass the seed to my script and the script with the seed passed to it is stored on-chain?
var img,inpt,div
function convertImgToDataURLviaCanvas(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
function convertFileToDataURLviaFileReader(url, callback){
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
}
function img2b64(imagefile){
var imageUrl = imagefile;
var convertType = 'Canvas';
var convertFunction = convertType === 'FileReader' ? convertFileToDataURLviaFileReader : convertImgToDataURLviaCanvas;
convertFunction(imageUrl, function(base64Img){
code='foto = "'+base64Img+'";'
inpt.value(code)
div.html('<img src="'+base64Img+'">');
});
}
function setup() {
but = createButton("CONVERT");
but.mousePressed(function () {
img2b64('nature100b.jpg');
});
inpt = createP('');
inpt = createElement("textarea",'');
inpt.elt.rows = 5;
inpt.elt.cols = 50;
div = createDiv('');
}
Try this
https://editor.p5js.org/josepssv/full/wsCZnJqkA

Preloading Images JavaScript

I am trying to preload images using Javascript. I am to suppose to use onload function and modularized coding. I have the codes below, but it does not seem to work. Any suggestions would greatly be appreciated. Thanks in advance.
function preloadImages() {
if (document.images) {
var img1 = new Image();
var img2 = new Image();
var img3 = new Image();
img1.src = "images/banner1.jpg";
img2.src = "images/banner2.jpg";
img3.src = "images/banner3.jpg";
}
}
function addLoadEvent(func) {
var loadImages = window.onload;
if (typeof window.onload != "function") {
window.onload = func;
} else {
window.onload = function() {
if (loadImages) {
loadImages();
}
func();
};
}
}
addLoadEvent(preloadImages);
I don't really know what you're trying to do. Perhaps this can help?
function ImgMaker(basePath){
this.img = function(url, doneFunc, errorFunc){
var img = new Image();
var b = basePath ? basePath.replace(/(\\|\/)$/) : '';
if(doneFunc)img.onload = doneFunc;
if(errorFunc)img.onerror = errorFunc;
img.src = b+url;
return img;
}
}
var doc, bod, im = new ImgMaker;
function noError(){
console.log(this.src+' loaded');
}
function error(){
console.log(this.src+" did't load");
}
addEventListener('load', function(){
doc = document; bod = doc.body;
bod.appendChild(im.img('img1.png', noError, error));
bod.appendChild(im.img('img2.png', noError, error));
bod.appendChild(im.img('img3.png', noError, error));
bod.appendChild(im.img('img4.png', noError, error));
bod.appendChild(im.img('img5.png', function(){
console.log(this.src+' loaded'); // showing anonymous way
// want async? load another image here
}, function(){
console.log(this.src+" didn't load");
}));
}); // end load

JavaScript set value to variable defined in parent function

i want to return imageSize but it is returning undefined. i am confused i have tried many things. in the alert i am getting size.
getImageSize : function(file) {
var reader = new FileReader();
var image = new Image();
var imageSize;
reader.readAsDataURL(file);
reader.onload = function(_file) {
image.src = _file.target.result;
image.onload = function() {
imageSize = ~~(file.size/1024) +'KB';
alert(imageSize);
};
};
return imageSize;
}
Since you are loading the image asynchronously, you cannot return the size directly. The best you can do is pass in a call-back function to be called when the size is available:
getImageSize : function(file, callback) {
var reader = new FileReader();
var image = new Image();
var imageSize;
reader.readAsDataURL(file);
reader.onload = function(_file) {
image.src = _file.target.result;
image.onload = function() {
imageSize = ~~(file.size/1024) +'KB';
callback(imageSize);
};
};
}

How can i add additional function parameters to assign attributes to an img?

This is a jquery plugin that i've found, that creates an img element and appends it to a parent element.
$.fn.loadImg = function(src, f){ return this.each(function(){ var i = new Image(); i.src = src; i.onload = f; this.appendChild(i);}); }
How can i add paramaters attrName, attrVal to the function that would assign whatever attributes to the image before appending it?
This should work:
$.fn.loadImg = function(src, f, attrName, attrVal) {
return this.each(
function() {
var i = new Image();
i.src = src;
i.onload = f;
i[attrName] = attrVal;
// alternatively:
// i.setAttribute(attrName, attrVal);
this.appendChild(i);
}
);
}

mouseover producing multiple images works in Firefox, but not i.e

The code below allows the user to hover over 1 object and it not only replaces the object but also shows an additional object between the buttons.
It works great in Firefox, but does not in Internet Explorer.
HELP
webpage:
http://www.isp.ucar.edu/
Thx,
Terri
if ( < document.images) {
img1on = new Image();
img1on.src = "images/buttons/button-beachon-on.gif";
img1off = new Image();
img1off.src = "images/buttons/button-beachon.gif";
img2on = new Image();
img2on.src = "images/buttons/button-bgs-on.gif";
img2off = new Image();
img2off.src = "images/buttons/button-bgs.gif";
img3on = new Image();
img3on.src = "images/buttons/button-iam-on.gif";
img3off = new Image();
img3off.src = "images/buttons/button-iam.gif";
img4on = new Image();
img4on.src = "images/buttons/button-nvia-on.gif";
img4off = new Image();
img4off.src = "images/buttons/button-nvia.gif";
img5on = new Image();
img5on.src = "images/buttons/button-utls-on.gif";
img5off = new Image();
img5off.src = "images/buttons/button-utls.gif";
img6on = new Image();
img6on.src = "images/buttons/button-water-on.gif";
img6off = new Image();
img6off.src = "images/buttons/button-water.gif";
img7on = new Image();
img7on.src = "images/buttons/button-exploratory-on.gif";
img7off = new Image();
img7off.src = "images/buttons/button-exploratory.gif";
// second image that does not appear in original button space
img1ad = new Image();
img1ad.src = "images/buttons/beachon-overview-sm.gif";
img2ad = new Image();
img2ad.src = "images/buttons/bgs-overview-sm.gif";
img3ad = new Image();
img3ad.src = "images/buttons/iam-overview-sm.gif";
img4ad = new Image();
img4ad.src = "images/buttons/nvia-overview-sm.gif";
img5ad = new Image();
img5ad.src = "images/buttons/utls-overview-sm.gif";
img6ad = new Image();
img6ad.src = "images/buttons/water-overview-sm.gif";
img7ad = new Image();
img7ad.src = "images/buttons/exploratory-overview-sm.gif";
}
function imgOn(imgName) {
if (document.images) {
document[imgName].src = eval(imgName + "on.src");
document["holder"].src = eval(imgName + "ad.src");
}
}
function imgOff(imgName) {
if (document.images) {
document[imgName].src = eval(imgName + "off.src");
document["holder"].src = "images/buttons/isp-overview-sm.gif";
}
}
First of all, eval in these functions are totally uncalled for
function imgOn(imgName) {
if ( < document.images) {
document[imgName].src = eval(imgName + "on.src");
document["holder"].src = eval(imgName + "ad.src");
}
}
function imgOff(imgName) {
if ( < document.images) {
document[imgName].src = eval(imgName + "off.src");
document["holder"].src = "images/buttons/isp-overview-sm.gif";
}
}
They should read
function imgOn(imgName) {
document.getElementById(imgName).src = window[imgName + "on"].src;
document.getElementById("holder").src = window[imgName + "ad"].src;
}
function imgOff(imgName) {
document.getELementById(imgName).src = window[imgName + "off"].src;
document.getElementById("holder").src = "images/buttons/isp-overview-sm.gif";
}
And instead of multiple img1on = new Image(); followed by calls to window[foo] you should do this
var myImages = {};
myImages["img1on" = new Image();
Then you can later on do
var foo = myImages[imgName + "on"].src;
to get the src.

Categories

Resources