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);
Related
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.
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 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
I have written this code in JavaScript and works perfectly fine when I include it on my index.html page:
<canvas id="bannerCanvas" width="960" height="200">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("bannerCanvas");
var context = canvas.getContext("2d");
context.beginPath();
context.moveTo(25,25);
context.lineTo(355,55);
context.lineTo(355,125);
context.lineTo(25,125);
context.moveTo(465,25);
context.fill();
};
</script>
...however when I place it in an external JavaScript file, it won't work! In the head of the index page, I have declared this:
<script type="text/javascript" src="JavaScript/functionality.js">
</script>
And I save this functionality.js file in the JavaScript directory, I've tried doing other JS functions in this file to check the index page and the JS are connected and they are...The answer is probably staring me in the face but for some reason I cannot see it!
Any help is much appreciated, thank you.
EDIT: I've been using Firebug and it is giving me no errors, when I use the code on the index page, I am seeing the shape I want yet when using the external JS file I am just seeing a big black rectangle.
the reason for this is that the script is being run before the canvas element is rendered.
To fix it, add this in your external file.
document.addEventListener('DOMContentLoaded',domloaded,false);
function domloaded(){
// your code here.
}
or with jquery
$(function(){
// your code here.
});
Within functionality.js, try wrapping your code in
window.onload = function() {
// code here
}
so that it won't execute until after the page has loaded.
If it is in the head, you are loading it before the canvas element is rendered. Look at the JavaScript console and you will see a Null or undefined error.
Add the script tag in the same place it works with the inline code. JavaScript does not have to live in the head and some developers will recommend it should always be the last thing in the body.
Other solution is to run the script on document ready or window onload.
Dont put in the head, When you put the code in the head, it run the code when there is no canvas element in page yet.