Resizing P5 Canvas according to image size - javascript

Please take a look at the following P5 code.
The point of this small app is to drag and drop an image on the canvas changing its size according to the "uploaded" image's width and height.
/**************************************************/
//GENERAL
var canvas;
//IMAGE
var img;//image
var imgW;//image width
var imgH;//image height
/**************************************************/
function setup(){
canvas = createCanvas(710, 400);//initial canvas size
canvas.drop(gotFile);
}
/**************************************************/
function draw(){
background(0);
if(img){
image(img, 0, 0);
imgW = img.width;
imgH = img.height;
if(imgW > 0 && imgH > 0){
resizeCanvas(imgW, imgH);
}
}
fill(255);
text(imgW + ", " + imgH, 10, 10);
}
/**************************************************/
//
function gotFile(file){
if (file.type === 'image') {
img = createImg(file.data).hide();
}
}
/**************************************************/
function mouseClicked(){
if(img){
if(imgW > 0 && imgH > 0){
resizeCanvas(imgW, imgH);
}
}
}
Using draw():
Once the image has been loaded successfully (at least displaying it), I assign its width and height to the variables imgW and imgH. Followed by the canvas size change... which leads to an error, the canvas' size the same as the uploaded image (checked on Developer Tools) but doesn't display anything.
Using mouseClicked():
When disabling the canvas size change on draw(), and click on the canvas, the resize happens perfectly showing the image.
The application needs to work without clicking, it should be automatic change (canvas size) after dropping the image.
UPDATE
This is what I see on the console when dropping the
The error I get on the console:
Uncaught RangeError: Maximum call stack size exceeded
at Array.map (<anonymous>)
at p5.Color._parseInputs (p5.js:44096)
at new p5.Color (p5.js:43147)
at p5.color (p5.js:42827)
at p5.Renderer2D.background (p5.js:50315)
at p5.background (p5.js:44288)
at draw (sketch.js:21)
at p5.redraw (p5.js:52435)
at p5.resizeCanvas (p5.js:51826)
at draw (sketch.js:30)
UPDATE 2
This is how the code looks like now, calling the resizeCanvas on the drop method:
/**************************************************/
//GENERAL
var canvas;
//IMAGE
var img;
var imgW;
var imgH;
var z;
/**************************************************/
function setup(){
canvas = createCanvas(710, 400);
canvas.drop(gotFile);
}
/**************************************************/
function draw(){
background(0);
//
if(img){
imgUpdate();
}
//debug
fill(255);
text(imgW + ", " + imgH, 10, 10);
}
/**************************************************/
function gotFile(file){
if (file.type === 'image') {
img = createImg(file.data).hide();
}
while (!img) {
}
createP("Uploaded");
if(img)
{
imgUpdate();
resizeCanvas(imgW, imgH);
}
}
/**************************************************/
function mouseClicked(){
if(img)
{
if(imgW > 0 && imgH > 0)
{
resizeCanvas(imgW, imgH);
}
}
}
/**************************************************/
function imgUpdate()
{
image(img, 0, 0);
imgW = img.width;
imgH = img.height;
}
/**************************************************/

The problem is the asynchronous loading of the image data. You can use the loadImage() method, take advantage of the success callback and write gotFile like this:
function gotFile(file){
if (file.type === 'image') {
img = loadImage(file.data,
function(){
imgUpdate();
resizeCanvas(imgW, imgH);
});
}
createP("Uploaded");
}

Keep in mind that the draw() function is called 60 times per second. It's also called whenever you call the resizeCanvas() function.
You call resizeCanvas() which calls draw() which calls resizeCanvas() which calls draw() until you eventually get your error.
To fix this, you need to stop calling resizeCanvas() every frame. It looks like you can probably call it from inside the gotFile() function instead?
Edit: After fixing that problem, your next problem is caused by the fact that JavaScript loads images asynchronously. Think about what happens on this line:
img = createImg(file.data).hide();
The createImg() file takes a URL, and begins loading the image in the background while your code continues to execute. Then you use img to resize the canvas, but the image isn't actually done loading yet, so the width and height are undefined. Try printing some values to the console to see what I mean.
To fix this problem, you need to wait until the image is actually loaded. I think you're trying to do that with your while loop, but note that your loop isn't doing much because img will always be defined the first time through. You need to go one level deeper and check the width and height of the image before you use it.
You could also use the p5.File reference to check the file type before continuing and do something like show a progress bar while the image loads.

Related

javascript canvas - check if images created with toDataURL() are loaded

I'm loading an image into my albImg array.
in my loop i then do this:
for(var j = 1; j < albImg.length; j++){
if(albImg[j].complete == true && albImg[j].width > 0){
loadedimages++;
}
}
to make sure all my images are loaded.
I then call my flipImg() function like this:
if(loadedimages == albImg.length-1){
flipImg();
}
I then flip an image and
ctx2.save();
ctx2.scale(-1, 1);
for (var i = RszSpriteCount; i < sprites.length; i++) {
ctx2.drawImage(albImg[sprites[i][0]], sprites[i][1], sprites[i][2], sprites[i][3], sprites[i][4], 0 - (sprites[i][1] + sprites[i][3]), sprites[i][2], sprites[i][3], sprites[i][4]);
}
ctx2.restore();
var flipSz = albImg.length;
albImg[flipSz] = new Image();
albImg[flipSz].src = cnv2.toDataURL();
Here's where my problem begins.
The new image I created - albImg[5] - can't be displayed until it is loaded.
But it is created as if it already is loaded.
That is to say that:
albImg[5].width is already set (to 750) before I can display it.
albImg[5].complete is set to true, before I can display it.
albImg[5].onload = ctx.drawImage(albImg[5], 0, 0); will try to draw the image before it is loaded.
How can I check if my flipped image really is loaded before I display it? in Javascript?
(due to circumstances I'm not using jQuery for this)
Please help.
Your main error is in how you do set the onload event handler :
albImg[5].onload = ctx.drawImage(albImg[5], 0, 0)
will set the return value of drawImage() (undefined) to the onload listener.
What you want is
albImg[5].onload = e => ctx.drawImage(albImg[5], 0, 0);
or
albImg[5].onload = function(){ ctx.drawImage(this, 0, 0) };
For the complete and width properties set to true, it's because while the loading of an Image is always async, in your case, the image is probably already HTTP cached.
Since the HTTP loading and the javascript execution are not executed on the same thread, it is possible that the Image actually loaded before the browser returns its properties.
But even then, the onload event will fire (best to set it before the src though).
var cacher = new Image();
cacher.onload = function(){
var img = new Image();
img.onload = function(){
console.log('"onload" fires asynchronously even when cached');
};
img.src = c.toDataURL();
console.log('cached : ', img.complete, img.naturalWidth);
}
cacher.src = c.toDataURL();
console.log('before cache :', cacher.complete, cacher.naturalWidth);
<canvas id="c"></canvas>
So when dealing with an new Image (not one in the html markup), always simply listen to its onload event.
Now, with the few information you gave in your question, it would seem that you don't even need these images, nor to deal with any of their loadings (except for the sprites of course), since you can directly and synchronously call ctx.drawImage(CanvasElement, x, y).
const ctx = c.getContext('2d');
ctx.moveTo(0, 0);
ctx.lineTo(300, 75);
ctx.lineTo(0, 150);
ctx.fillStyle = 'rgba(120,120,30, .35)';
ctx.fill();
const flipped = c.cloneNode(); // create an offscreen canvas
const f_ctx = flipped.getContext('2d');
f_ctx.setTransform(-1, 0,0,1, c.width, 0);// flip it
f_ctx.drawImage(c,0,0);// draw the original image
// now draw this flipped version on the original one just like an Image.
ctx.drawImage(flipped, 0,0);
// again in 3s
setTimeout(()=>ctx.drawImage(flipped, 150,0), 3000);
<canvas id="c"></canvas>

image smaller than the original on canvas to make drawImage()

I am developing a system for image filter with html5 canvas, however, as I am at the beginning I have emerged me some doubts and mistakes.
Here's what I've developed so far:
$(document).ready(function() {
$("#uploadImagem").change(function(e) {
var _URL = window.URL || window.webkitURL,
arquivo = e.target.files[0],
tipoImagem = /image.*/,
reader,
imagem;
if(!arquivo.type.match(tipoImagem)) {
alert("Somente imagens são aceitas!");
return;
}
imagem = new Image();
imagem.onload = function() {
if(this.width > 600 || this.height > 400) {
alert("Somente imagens com largura máxima de 600px e altura máxima de 400px");
return;
} else {
$("#filtrarImagem").width(this.width).height(this.height);
}
};
imagem.src = _URL.createObjectURL(arquivo);
reader = new FileReader();
reader.onload = fileOnload;
reader.readAsDataURL(arquivo);
});
function fileOnload(e) {
var $img = $("<img>", {src: e.target.result}),
canvas = $("#filtrarImagem")[0],
context = canvas.getContext("2d");
$img.load(function() {
context.drawImage(this, 0, 0);
});
}
});
When I do imagem.onload... I wish, if the image pixels were greater than 600 and 400 he gave the alert and stop there, but even so the image appears on the canvas.
In the same imagem.onload... function, if the image pixels correspond to the canvas required (id = "filtrarImagem") is the size of the image, but the image to the canvas becomes smaller than the original uploaded, and she was to occupy all the canvas and get the original size.
How to continue?
You have two separate handlers for image loading. There is no need to set two image sources with the same URL, just reuse a single image for both checking size and setting canvas size as well as draw it into the canvas.
I would suggest the following steps (you tagged the question with jQuery but I would highly recommend working in vanilla JavaScript when you work with non-DOM oriented elements such as canvas).
Example
if (typeof window.URL === "undefined") window.URL = window.webkitURL;
$("input")[0].onchange = function(e) {
var arquivo = e.target.files[0],
imagem = new Image();
if (!arquivo.type.match(/image.*/)) {
alert("Somente imagens são aceitas!");
return;
}
// STEP 1: load as image
imagem.onload = doSetup;
imagem.src = URL.createObjectURL(arquivo)
};
// STEP 2: now that we have the image loaded we can check size and setup canvas
function doSetup() {
URL.revokeObjectURL(this.src); // clean up memory for object-URL
if (this.width > 600 || this.height > 400) {
alert("Too big!");
return; // exit!
}
// image OK, setup canvas
var c = $("canvas")[0]; // work with the element itself, not the jQuery object
c.width = this.width; // important: use canvas.width, not style or css
c.height = this.height;
// draw in image
var ctx = c.getContext("2d");
ctx.drawImage(this, 0, 0);
// NEXT: ... from here, invoke filter etc.
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file"><br><canvas></canvas>
The jQuery width() and height() functions use CSS to change the size of the canvas which does not do what you would expect it to do. Change the width and height attributes of the canvas element directly.
The reason why your check for the size does not prevent the image from being drawn, is because your check is in the handler for imagem.onload in $("#uploadImagem").change while the drawing happens in $img.onload assigned from reader.onload. These two events are processed independently. One of them returning prematurely does not prevent the other from being executed.

Scaling HTML5 Canvas Image

Building a web page on which I am trying to set an image as the background of the main canvas. The actual image is 1600x805 and I am trying to code the application so that it will scale the image either up or down, according to the dimensions of the user's screen. In Prime.js I have an object that sets the properties of the application's canvas element located in index.html. Here is the code for that object:
function Prime(w,h){
if(!(function(){
return Modernizr.canvas;
})){ alert('Error'); return false; };
this.context = null;
this.self = this;
this.globalCanvasMain.w = w;
this.globalCanvasMain.h = h;
this.globalCanvasMain.set(this.self);
this.background.setBg();
}
Prime.prototype = {
constructor: Prime,
self: this,
globalCanvasMain: {
x: 0,
y: 0,
set: function(ref){
ref.context = document.getElementById('mainCanvas').getContext('2d');
$("#mainCanvas").parent().css('position', 'relative');
$("#mainCanvas").css({left: this.x, top: this.y, position: 'absolute'});
$("#mainCanvas").width(this.w).height(this.h);
}
},
background: {
bg: null,
setBg: function(){
this.bg = new Image();
this.bg.src = 'res/background.jpg';
}
},
drawAll: function(){
this.context.drawImage(this.background.bg, 0,0, this.background.bg.width,this.background.bg.height,
this.globalCanvasMain.x,this.globalCanvasMain.y, this.globalCanvasMain.w,this.globalCanvasMain.h);
}
};
The primary interface through which external objects like this one will interact with the elements in index.html is home.js. Here's what happens there:
$(document).ready(function(){
var prime = new Prime(window.innerWidth,window.innerHeight);
setInterval(prime.drawAll(), 25);
});
For some reason, my call to the context's drawImage function clips only the top left corner from the image and scales it up to the size of the user's screen. Why can I not see the rest of the image?
The problem is that the image has probably not finished loading by the time you call setInterval. If the image is not properly loaded and decoded then drawImage will abort its operation:
If the image isn't yet fully decoded, then nothing is drawn
You need to make sure the image has loaded before attempting to draw it. Do this using the image's onload handler. This operation is asynchronous so it means you also need to deal with either a callback (or a promise):
In the background object you need to supply a callback for the image loading, for example:
...
background: {
bg: null,
setBg: function(callback) {
this.bg = new Image();
this.bg.onload = callback; // supply onload handler before src
this.bg.src = 'res/background.jpg';
}
},
...
Now when the background is set wait for the callback before continue to drawAll() (though, you never seem to set a background which means drawImage tries to draw null):
$(document).ready(function(){
var prime = new Prime(window.innerWidth, window.innerHeight);
// supply a callback function reference:
prime.background.setBg(callbackImageSet);
// image has loaded, now you can draw the background:
function callbackImageSet() {
setInterval(function() {
prime.drawAll();
}, 25);
};
If you want to draw the complete image scaled to fit the canvas you can simplify the call, just supply the new size (and this.globalCanvasMain.x/y doesn't seem to be defined? ):
drawAll: function(){
this.context.drawImage(this.background.bg, 0,0,
this.globalCanvasMain.w,
this.globalCanvasMain.h);
}
I would recommend you to use requestAnimationFrame to draw the image as this will sync with the monitor update.
Also remember to provide callbacks for onerror/onabort on the image object.
There is a problem with the setInterval function. You are not providing proper function reference. The code
setInterval(prime.drawAll(), 25);
execute prime.drawAll only once, and as the result only little part of the image which is being loaded at this moment, is rendered.
Correct code should be:
$(document).ready(function(){
var prime = new Prime(window.innerWidth, window.innerHeight);
setInterval(function() {
prime.drawAll();
}, 25);
});

INDEX_SIZE_ERR when drawImage on canvas

I need to draw an Image object to a canvas but I've got an INDEX_SIZE_ERR exception in Firefox and IE10 but not in Chrome nor Safari...
According to the W3C: If one of the sw or sh arguments is zero, the implementation must raise an INDEX_SIZE_ERR exception..
Here is the code that causes the problem:
function writePhotoOnCanvas(data, width, height) {
// Get the canvas
var canvasGallery = document.getElementById("canvasGallery");
// Clear the canvas
canvasGallery.width = canvasGallery.width;
// Get its context
var ctxCapture = canvasGallery.getContext("2d");
// Create an image in order to draw in the canvas
var img = new Image();
// Set image width
img.width = width;
// Set image height
img.height = height;
// To do when the image is loaded
img.onload = function() {
console.log("img.width="+img.width+", img.height="+img.height);
console.log("width="+width+", height="+height+", canvasGallery.width="+canvasGallery.width+", canvasGallery.height="+canvasGallery.height);
// Draw the picture
try {
ctxCapture.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvasGallery.width, canvasGallery.height);
} catch(e) {
console.error(e.message);
}
};
// Set image content from specified photo
img.src = data;
}
The console shows:
img.width=640, img.height=480
width=640, height=480, canvasGallery.width=589, canvasGallery.height=440
Index or size is negative or greater than the allowed amount
What is the source of the problem?
Thanks
You are manually setting the width and height of the image (img.width = width; img.height = height;). I don't really understand why you are doing this, but it is likely unnecessary.
These should be calculated automatically from the image data you load. Try to remove them to see what the actual size of the data is.
The image width and height are read-only properties so they will cause the code to break in some browser.
If you absolutely want to set the width and height before loading the image you can do:
var img = new Image(width, height);
Then you can read img.width and img.height when image has loaded (or read img.naturalWidth and img.naturalHeight to get the original dimension).
There is no need though to do this. Simply call your drawImage() like this:
ctxCapture.drawImage(img, 0, 0, canvasGallery.width, canvasGallery.height);
This will use the full dimension of the image and scale it to the canvasGallery's dimension.
Tip: If you are using this function to load several images you will want to exchange img with this inside your onload handler.
Modified code:
function writePhotoOnCanvas(data, width, height) {
var canvasGallery = document.getElementById("canvasGallery");
var ctxCapture = canvasGallery.getContext("2d");
/// setting width to clear does not work in all browser, to be sure:
ctxCapture.clearRect(0, 0, canvasGallery.width, canvasGallery.height);
var img = new Image();
img.onload = function() {
// Draw the picture
try {
ctxCapture.drawImage(this, 0, 0,
canvasGallery.width, canvasGallery.height);
} catch(e) {
console.error(e.message);
}
};
// Set image content from specified photo
img.src = data;
}

jQuery and Canvas loading behaviour

After being a long time lurker, this is my first post here! I've been RTFMing and searching everywhere for an answer to this question to no avail. I will try to be as informative as I can, hope you could help me.
This code is for my personal webpage.
I am trying to implement some sort of a modern click-map using HTML5 and jQuery.
In the website you would see the main image and a hidden canvas with the same size at the same coordinates with this picture drawn into it.
When the mouse hovers the main picture, it read the mouse pixel data (array of r,g,b,alpha) from the image drawn onto the canvas. When it sees the pixel color is black (in my case I only check the RED value, which in a black pixel would be 0) it knows the activate the relevant button.
(Originally, I got the idea from this article)
The reason I chose this method, is for the page to be responsive and dynamically change to fit different monitors and mobile devices. To achieve this, I call the DrawCanvas function every time the screen is re-sized, to redraw the canvas with the new dimensions.
Generally, this works OK. The thing is ,there seems to be an inconsistent behavior in Chrome and IE(9). When I initially open the page, I sometimes get no pixel data (0,0,0,0), until i re-size the browser. At first I figured there's some loading issues that are making this happen so I tried to hack it with setTimeout, it still doesn't work. I also tried to trigger the re-size event and call the drawCanvas function at document.ready, still didn't work.
What's bothering me is most, are the inconsistencies. Sometimes it works, sometimes is doesn't. Generally, it is more stable in chrome than in IE(9).
Here is the deprecated code:
<script type="text/javascript">
$(document).ready(function(){setTimeout(function() {
// Get main image object
var mapWrapper = document.getElementById('map_wrapper').getElementsByTagName('img').item(0);
// Create a hidden canvas the same size as the main image and append it to main div
var canvas = document.createElement('canvas');
canvas.height = mapWrapper.clientHeight;
canvas.width = mapWrapper.clientWidth;
canvas.fillStyle = 'rgb(255,255,255)';
canvas.style.display = 'none';
canvas.id = 'hiddencvs';
$('#map_wrapper').append(canvas);
// Draw the buttons image into the canvas
drawCanvas(null);
$("#map_wrapper").mousemove(function(e){
var canvas = document.getElementById('hiddencvs');
var context = canvas.getContext('2d');
var pos = findPos(this);
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
// Get pixel information array (red, green, blue, alpha)
var pixel = context.getImageData(x,y,1,1).data;
var red = pixel[0];
var main_img = document.getElementById('map_wrapper').getElementsByTagName('img').item(0);
if (red == 0)
{
...
}
else {
...
}
});
},3000);}); // End DOM Ready
function drawCanvas(e)
{
// Get context of hidden convas and set size according to main image
var cvs = document.getElementById('hiddencvs');
var ctx = cvs.getContext('2d');
var mapWrapper = document.getElementById('map_wrapper').getElementsByTagName('img').item(0);
cvs.width = mapWrapper.clientWidth;
cvs.height = mapWrapper.clientHeight;
// Create img element for buttons image
var img = document.createElement("img");
img.src = "img/main-page-buttons.png";
// Draw buttons image inside hidden canvas, strech it to canvas size
ctx.drawImage(img, 0, 0,cvs.width,cvs.height);
}
$(window).resize(function(e){
drawCanvas(e);
}
);
function findPos(obj)
{
...
}
</script>
I'd appreciate any help!
Thanks!
Ron.
You don't wait for the image to be loaded so, depending on the cache, you may draw an image or not in the canvas.
You should do this :
$(function(){
var img = document.createElement("img");
img.onload = function() {
var mapWrapper = document.getElementById('map_wrapper').getElementsByTagName('img').item(0);
...
// your whole code here !
...
}
img.src = "img/main-page-buttons.png";
});

Categories

Resources