So, I'm trying to programmatically add an image to my canvas, from a Javascript function :
// Spawn function
var spawnWrapper = function() {
myCanvas = Processing.getInstanceById('mycanvas');
// myCanvas.ellipse(50,50,50,50); // works fine here too
myImage = myCanvas.loadImage('pegman.png');
myCanvas.image(myImage,0,0);
};
The same successive calls in console works :
Also, there are no errors mentioned on the console.
I'm really stuck there and would appreciate any help ;-)
I suspect that you might be missing the preload directive.
This directive regulates image preloading, which is required when
using loadImage() or requestImage() in a sketch. Using this directive
will preload all images indicated between quotes, and comma separated
if multiple images are used, so that they will be ready for use when
the sketch begins running.
I hope that helps. I'm curious as to why you're using processing.js instead of P5.js?
Good luck.
Related
I have an image tag in my HTML code with src containing the path to a local image.
<img alt="abc" src="./images/abc.png" />
Upon clicking the image, I want to call a JavaScript method that will return the buffer data of the image.
Example buffer:
(23234)[234,345,786]
How is it done in pure JavaScript?
You can not read pixels from an image, but you can draw an image to a canvas, and use getImageData to extract an array of the RGBA pixel data. Then it is possible to get color under the mouse cursor.
Notes about the example below:
the image is tiny because getImageData has cross-origin protection, and as uploading images for examples does not seem to be possible, the image is encoded in a data URI
however data URI-s also have cross-origin issues in certain browsers, like IE (it will not with IE as far as I remember). I tested the code with Chrome, so that works for sure, and I think it should work with Firefox too
none of these matters with real life code, so if you get this code out from here, and just write <img src="something.jpg" ... (so hosted locally), it can be a large image and it will work with IE too
there is some race condition here, sometimes I get messages about missing imgready function, so StackOverflow may load the HTML first and inject the scripts later. If you see that message, run the snippet again. With more "traditional" code order (scripts located in head) it could not happen
var imgdata;
function imgready(){
var img=document.getElementById("you");
var cnv=document.createElement("canvas");
var w=cnv.width=img.width;
var h=cnv.height=img.height;
var ctx=cnv.getContext("2d");
ctx.drawImage(img,0,0);
imgdata=ctx.getImageData(0,0,w,h);
}
function mmove(event){
if(!imgdata)return;
var x=event.clientX-event.target.offsetLeft;
var y=event.clientY-event.target.offsetTop;
var offset=(x+y*imgdata.width)*4;
var r=imgdata.data[offset];
var g=imgdata.data[offset+1];
var b=imgdata.data[offset+2];
document.getElementById("logdiv").innerText=x+","+y+" ("+offset+"): r="+r+" g="+g+" b="+b;
var cnv=document.getElementById("colorcnv");
var ctx=cnv.getContext("2d");
ctx.clearRect(0,0,cnv.width,cnv.height);
ctx.fillStyle="rgb("+r+","+g+","+b+")";
ctx.beginPath();
ctx.arc(10,10,10,0,Math.PI*2);
ctx.fill();
}
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4QAqRXhpZgAASUkqAAgAAAABADEBAgAHAAAAGgAAAAAAAABHb29nbGUAAP/bAIQAAwICAwICAwMDAwQDAwQFCAUFBAQFCgcHBggMCgwMCwoLCw0OEhANDhEOCwsQFhARExQVFRUMDxcYFhQYEhQVFAEDBAQFBAUJBQUJFA0LDRQUFBQUExQPFBQUFBQUFBQUFBQUFBQUEBUUFBQVDxQUFA4UFBQVFBEVFBQTFBQUERQU/8AAEQgAFAAUAwERAAIRAQMRAf/EABoAAAEFAQAAAAAAAAAAAAAAAAgEBQYHCQP/xAAnEAABAwMEAQMFAAAAAAAAAAABAgMFBBEhAAYHEmETIjEII0FCof/EABkBAAIDAQAAAAAAAAAAAAAAAAQGAwUHAv/EACwRAAEDAwIDBgcAAAAAAAAAAAECAxEABCExUQUGEkFhweHw8RMiMnGBsdH/2gAMAwEAAhEDEQA/AM6GuRZOaplxjVGyh2oQWkuNEhQxm3m2NVhtUNHrJwKPDql/KBVkO/SDPDa9DKRM9QyMm+EOCLbSUOtNFQBeKrmyR83tnqbXItpbb5nZLpbeaKUyROudojt98VZq4QtKAptYJ1inWqjEsVC2i428WyUF1o3Qu2OyTYYPyNGJV1CRiuYjFRSf4KmuERszcM49RvOzdIJOgj2qhtai0W0KBc6LUW7esgWUkEnsAD1JDOi3evVFgCJ7Z8KqSWmEhwKk7R40SXB3M8NOcPbm2puGoVB1VLQ1b7zTTQSiqZKlOKSwv9VdlC4JTg4CsqTn/HuWb3h9wi4t09SCpIB1IOAOoffAORvGlMVpxVm5a+C4YUAZ79Tj1/aGyOl9xGjbK32XV2ytbIyfFrY8/nW0K5aszmFD8+RpUTfORSrdG5ZvccjGtzM7LTbVBQKYo25Svdq00rVh9toOKV6aPan2psMDGg+GmHFK2FDOfTXCnYQaZN09u1yQrOQQR/dPgSClJ7/36mgN6WvrU2vrcqsPk6kccKVECpUiRX//2Q==" id="you" onload="imgready()" onmousemove="mmove(event)">
<canvas id="colorcnv" width="20" height="20"></canvas><br>
<div id="logdiv"></div>
Modified version of tevemadar's answer that might be usefull:
function imgToBuffer(e){
let cnv=document.createElement("canvas"), w=cnv.width=e.width, h=cnv.height=e.height, ctx=cnv.getContext("2d");
ctx.drawImage(e,0,0);
return getImageData(0,0,w,h)
}
This function simply draws the image element to canvas and returns the image buffer. No extra HTML needed.
To get the ArrayBuffer out of it, use
imgToBuffer(el).data.buffer
I have done the following code to convert HTML Content(DIV) to save as Image (JPEG, PNG,GIF Etc) with below code.
<pre>
html2canvas($(".mainbox"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
Canvas2Image.saveAsImage(canvas);
$("#FinalImage").append(canvas);
}
});
</pre>
I have also included html2canvas.js,base64.js and canvas2image.js in my page. At the end Image is shown in #FinalImage DIV and browser ask me to save it in my drive up to now all are working fine.
Now the question is name of the saved image has no Extension, every time I need to go to the image and assign the Extension(".jpg",".png" etc...). Is there any solution to set extension by default when user saves from the browser.
Thanks in advance.
I have done same functionality for capturing signature. This is different from your approach. but this code snippet may help you. plz comment if u need whole source code.
var canvas = document.getElementById(<canvas element id>)// get canvas element
var dataURL = canvas.toDataURL("image/png");// convert to img, specify extension
document.getElementById(<new image id>).src = dataURL; // write as an image
In line two I specified png.there you can change the extension of image. Hope it helps
I'm making an Android game, in HTML5 and Javascript, I am part of the way there, but have hit something that has stumped me, My JS file and my Html file were working together, to draw on the canvas etc, but now I'm trying to draw an image on the canvas, nothing is being displayed, I know the img function is being found, as, alert (img);, works so it's just lost on me. (currently this is copied from a book I was given at college, and it's identical, the JS has been verified in JSHint and passes, so I'm lost) also, please be quite simple, I'm pretty new to JS but have used html for a long time, and this just has to be a simple game for a college assignment.
My HTML code is
<canvas id="game" width="1024" height="600">Sorry, your browser does not support this</canvas>
and my JS is:
function init() {
var elem = document.getElementById('game');
var canvas = elem.getContext('2d');
var img = document.createElement('img');
img.setAttribute('src', 'http://www.minkbooks.com/content/snow.jpg');
img.addEventListener("load", function() {
canvas.drawImage(img, 20, 20);
alert(canvas);
});
}
addEventListener("load", init);
and here it is on JSfiddle: http://jsfiddle.net/xw8m7/
This answer is based on your jsfiddle. You are executing your javascript code as soon as it is loaded. Depending on where your code is located in the html, the canvas element might not be loaded yet, and that would prevent your code from loading the image into the canvas element, and you would still get the alert.
In JSFiddle, you need to set the option of running your code "onDomready". That means that the JavaScript won't run until everything has been loaded (your canvas element). After changing that in your jsfiddle, your function loaded the image into the canvas just fine.
Update:
Based on your comment about XDK, I found a bit of example code and modified it. Original source: https://software.intel.com/en-us/node/493117
document.addEventListener("intel.xdk.device.ready",function(){
init();
},false);
I have these 3 lines of code in an external javascript file
function init(){
document.getElementById("upcoming_event").getElementsByTagName("img")[0].src = "images/fastnet_2013_poster.jpg";
document.getElementById("club_championship").getElementsByTagName("img")[0].src = "images/club_championship.png";
document.getElementById("setMembership").getElementsByTagName("img")[0].src = "images/join_our_club.png";
}
document.addEventListener( "DOMContentLoaded" , init , false);
This code works perfectly on this site which i used just to develop a little bit of it with 000webhosting.
But I have now moved my hosting to hosting24 to complete the development of the site. When i load the site through the new host(hosting24) the images are not getting loaded.
I have taken these 3 line of code out and tried them in an <body onload="init()"> but this dose not load the images either.
I know that both methods above are being called as i have got them to display a window.alert("Display").
Is there another way of doing this?
(document.getElementById("upcoming_event").getElementsByTagName("img")[0].src = "images/fastnet_2013_poster.jpg";) that i could try and use? Or solve my problem.
Changing servers should not effect javascript code at all. Only thing that comes to mind is that the URL's for the images sources isn't correct anymore, because of the move.
First you can use jQuery to help you do this in a simpler way like:
$('#upcoming_event').find('img')[0].src = "url";
or
$('#imgid').attr('src', 'xpto.jpg');
Secound, the code seems to work... I think the problem may be in the urls of the IMGs. Check if the images are in the correct folder or if the path is right.
I have really strange problem. I'm trying to get width and height of an image using following way:
Create a image tag and add .src to it.
add this image tag to document.body.
making this image tag visible (display:inline).
getting .offsetWidth and .offsetHeight of element.
hidding image tag(display:none);
all this is done using JS and it all work really well on my localhost, but when I uploaded a site to my client hosting provider I was amazed. offsetWidth and .offsetHeight was 0 in step 4. Why do that happen? I think that I need some kind of "flush" after step 3 before step 4, but I'm not exactly sure. Any suggestions ? Thank you.
You have to wait for the image to actually load over the network. You don't need to add the thing to the DOM either:
var img = new Image();
img.onload = function() {
handleImageSize(this.width, this.height);
};
img.src = "http://whatever.com/your/img.jpg";
Here, "handleImageSize" would be a function you write to do whatever it is you need to do with the image dimensions.
This was probably caused by the image not being loaded yet. Try something like this:
img.onload = function() {
// get the offsetWidth and offsetHeight
}
As other answers suggest, is due to the image not being fully loaded by the DOM. This was working fine on your local server as I suspect you were loading images locally, meaning they were almost instantaneous; however after moving them to the server there is a slight delay. It's an easily overlooked problem, that is easily fixed.
Other answers will do the trick; but here's the jQuery version for sake of argument
var img = $('<img>', {
src: 'http://dummyimage.com/150/000/fff.gif'
}).one('load', function() {
var offsets = $(this).offset();
});
$('body').append(img);
jsFiddle