JavaScript Image not drawing to canvas - javascript

I am just being a complete noob and been looking around for a answer. "ctx.fillRect(0,0,100,100);" works which mean ctx was declared correctly and "test()" is being called. I just don't understand why the image wont draw.
var Img = new Image();
Img.scr ='/client/Assets/StartScreen/Background.png'; //This URL was tested via html img tag
function test(){
ctx.fillStyle = 'blue';
ctx.fillRect(0,0,100,100); //THIS WORKS
ctx.drawImage(Img,0,0,600,600); // Will not load
}

Img.scr ='/client/Assets/StartScreen/Background.png'; //This URL was tested via html img tag
Img.scr undefined property. You should try with Img.src
Img.src ='/client/Assets/StartScreen/Background.png';

Two things:
Your code had img.scr, not img.src.
Image loading happens asynchronously; you'll need to wait for the image to be complete (img.complete). You can use the onload event listener to draw things the instant the image is ready.
var img = new Image();
img.src = "/client/Assets/StartScreen/Background.png";
function draw() {
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 100, 100);
ctx.drawImage(img, 0, 0, 600, 600);
}
img.onload = function() {
draw();
};

You should add image to canvas only when it is loaded.
try,
var Img = new Image();
Img.src ='/client/Assets/StartScreen/Background.png';
Img.onload = function() {
test();
}
function test(){
ctx.fillStyle = 'blue';
ctx.fillRect(0,0,100,100);
ctx.drawImage(Img,0,0,600,600);
}

Related

Why is this appearing behind the canvas instead of drawing over it?

I am working on a dynamic web map with HTML5 and canvas.
I loaded the map in PNG format, but whenever I try to draw on it, it draws behind the map like this:
I need it to draw over the white squares.
This is my code:
window.onload = function() {
var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
img.src = "img/plano.png"; //transparent png
ctx.fillRect(1039, 150, 50, 50);
}
Thanks in advance!
The fillRect needs to happen after the image has loaded. The image loads asynchronously so the only safe place for this to happen is after the drawImage...
img.onload = function() {
ctx.drawImage(img, 0, 0);
ctx.fillRect(200,200,50,50); // Draw rect after image
}

Unable to load an Image into Canvas and get base64 encoding for that image

I am trying to generate a PDF from HTML using jspdf plugin. I am stuck with loading Images into PDF. There is a function addImage() in plugin which takes base64 encoding of an image, but converting an image to base64 is not working.
I have used below two ways
//Create canvas, draw image in context and get the data url
imgToDataURL = function (img, outputFormat){
var canvas = document.createElement('canvas');
canvas.width = 20;
canvas.height = 20;
var c = canvas.getContext('2d');
c.height = img.height;
c.width=img.width;
c.drawImage(img, 0, 0);
c.save();
var dataurl = canvas.toDataURL(outputFormat);
return dataurl;
}
var img = new Image();
img.crossOrigin = 'Anonymous';
img.src = "image path"
img.height= 60;
img.width=60;
var dataURL = this.imgToDataURL(img,"image/jpeg");
renderer.pdf.addImage(dataURL, 'png',x+padding,y + this.internal.getLineHeight(),imageWidth,imageHeight);
This is printing wrong dataURL I am getting a white image. If I hard code the base64 code i.e return a hardcoded dataURL then addImage works fine. So the issue is with canvas.toDataURL which is giving me wrong output
this is the 2nd way
convertImgToBase64URL = function (url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'), 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;
}
this.convertImgToBase64URL("Image Path",function(base64){
renderer.pdf.addImage(base64, 'PNG', 20, 20,48,48);
})
I have run this inside a javascript and the onload function is not even running I am not sure what is my mistake is.
Please suggest me what mistake I am doing in either way
In the first you missed assigning an onload function to your image. For that reason, the moment you try to create the dataURL, the image might not be loaded yet, ergo, the blank image. You could try changing the last few lines to this:
...
img.width=60;
img.onload = function () {
var dataURL = this.imgToDataURL(img,"image/jpeg");
renderer.pdf.addImage(dataURL, 'png',x+padding,y + this.internal.getLineHeight(),imageWidth,imageHeight);
}
img.src = "image path";
As for the second one, there seems to be a problem with the convertImgToBase64URL() which accepts 3 parameters, but you are passing 2. In you example, outputFormat parameter is undefined.

rendering canvas in firefox not working [duplicate]

I try to build a javascript code, to draw a image on canvas, but I don't know where go wrong.
That is my code:
<body>
<canvas id = "my_canvas"></canvas>
<script>
function setup(){
var canvas = document.getElementById('my_canvas');
var ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;
var image = new Image();
image.src = 'a.png';
ctx.drawImage(image,5,5);
};
window.onload = setup;
setup();
</script>
The question is, if I put a line of code setup(); at end then the image is correctly draw, I don't know why.
Thanks.
The problem is that image is loaded asynchronously, so if you set the source and draw it immediately then the image bits are not yet available and nothing is drawn.
You have to wait for the image to load before being able to draw it on a canvas.
Changing the code to
image.onload = function() {
ctx.drawImage(image, 5, 5);
};
image.src = "a.png";
should work as expected.
The image is loading asynchronously. This code will work:
JavaScript:
function setup(){
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;
var image = new Image();
image.onload = function () {
ctx.drawImage(image,5,5);
};
image.src = 'a.png';
}
window.onload = setup;

Local Cross-origin data error

I'm trying to make a game in JavaScript and i need to get pixeldata from an image. i'm using getImageData().data; and it is working all good on Internet Explorer, but on Chrome i get this error:
Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
I've been looking around for solutions but nothing seems to work, anyone have a good idea?
here is my code: `
var
width = 600,
height = 400,
img,
canvas,
ctx;
function main() {
canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
document.body.appendChild(canvas);
init();
loop();
}
function init() {
img = new Image();
img.src = "test.png";
}
function update() {
}
function render() {
ctx.drawImage(img, 0, 0);
var data = ctx.getImageData(10, 10, 1, 1).data;
console.log(data);
}
function loop() {
window.requestAnimationFrame(loop);
update();
render();
}
main();`
The file is running localy and not on a server.
If you load your page or file using file://... it will trigger CORS issues as well.
When testing locally, always use a local server so you can load the files from localhost.
Also a side issue: remember to use the onload handler for the image:
function init() {
img = new Image();
img.onload = ... // don't start loop without it...
img.src = "test.png";
}
Try it:
function init() {
img = new Image();
img.crossOrigin = "Anonymous";
img.src = "test.png";
}

Displaying one canvas to another

I have a problem displaying one canvas to another. I do everything according to this solution
<script>
var source = document.getElementById('hiddenCanvas');
var source_ctx = source.getContext('2d');
var img = new Image();
img.onload = function(){
source.width = img.width;
source.height = img.height;
source_ctx.drawImage(img, 0, 0, img.width, img.height);
}
img.src = 'icon.jpg';
var destination = document.getElementById('visibleCanvas');
var destin_ctx = destination.getContext('2d');
destin_ctx.drawImage(source, 0, 0);
</script>
Well, first canvas element displays picture correctly, but whatever I do, the second canvas does not want to display a picture.
<script>
function init()
{
var source = document.getElementById('hiddenCanvas');
var source_ctx = source.getContext('2d');
var destination = document.getElementById('visibleCanvas');
var destin_ctx = destination.getContext('2d');
var img = new Image();
img.onload = function(){
source.width = img.width;
source.height = img.height;
source_ctx.drawImage(img, 0, 0, img.width, img.height);
destin_ctx.drawImage(source, 0, 0);
}
img.src = 'arun.jpg';
}
</script>
</head>
<body onload="init();">
<canvas id="hiddenCanvas" />
<canvas id="visibleCanvas" />
Your code is not working because you are trying to access canvas element before it is loaded to dom
The way you've currently structured the code, img.onload is executed after the destin_ctx.drawImage line. That means that your program flow currently looks something like this:
Image is told to start loading
Destination canvas is drawn using (currently blank) source canvas
Image finishes loading
Image's onload executes, causing the source canvas to be drawn to. The destination canvas is NOT updated, because the destin_ctx.drawImage operation is a one-time copy.
What you need to do is move the destin_ctw.drawImage call to a place in the execution flow where you know the source canvas will definitely contain the appropriate contents. In this simple case, moving it to inside the image's onload would work.
Here's a full (but simplified) HTML file that works for me in Chromium, with a changed image url:
<script>
function load() {
var source = document.getElementById('hiddenCanvas');
var source_ctx = source.getContext('2d');
var destination = document.getElementById('visibleCanvas');
var destin_ctx = destination.getContext('2d');
var img = new Image();
img.onload = function(){
source.width = img.width;
source.height = img.height;
source_ctx.drawImage(img, 0, 0, img.width, img.height);
destin_ctx.drawImage(source, 0, 0);
}
img.src = 'ship360_32.png';
}
</script>
<body onload="load()">
<canvas id="hiddenCanvas"></canvas>
<canvas id="visibleCanvas"></canvas>
</body>
You are trying to draw the image from source before the image is loaded and the source even have the image.
Move the last draw operation inside the onload handler. Also remember to set the size for destination canvas:
var source = document.getElementById('hiddenCanvas');
var source_ctx = source.getContext('2d');
var destination = document.getElementById('visibleCanvas');
var destin_ctx = destination.getContext('2d');
var img = new Image();
img.onload = function(){
source.width = img.width;
source.height = img.height;
source_ctx.drawImage(img, 0, 0, img.width, img.height);
destination.width = source.width;
destination.height = source.height;
destin_ctx.drawImage(source, 0, 0);
}
img.src = 'icon.jpg';

Categories

Resources