Why is my image not showing on the canvas? - javascript

I am trying to show an image on a canvas at the top corner and the draw function is not working properly. What have I done wrong.
The above image is what I want to show on the screen.
<html>
<head>
<title></title>
</head>
<body>
<p><canvas id="canvas" style="border:1px solid black;" width="450" height="310"></canvas>
</body>
<script>
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
draw();
function draw(){
var img = new Image();
img.src = "t.gif";
ctx.drawImage(img,0,0);
}
</script>
</html>

The problem is that you attempt to draw the image immediately, before the browser has finished downloading it.
Try this instead:
function draw(){
var img = new Image();
img.onload = function() {
ctx.drawImage(img,0,0);
};
img.src = "t.gif";
}

You should draw image after it is loaded
img.onload = function() {
// here...
};

Related

Get base64 data of image inside a canvas

I know this question is asked man times but my problem is this. I want to get data of image inside a canvas and get that! But when I change the image resource derived data does not change. In an other words it doesn't matter what image I use in my code. For best understanding my question my code is below.
<!DOCTYPE html>
<html>
<body>
<canvas id="viewport" style="border:1px solid #d3d3d3;"></canvas>
<script>
var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');
make_base();
function make_base()
{
base_image = new Image();
base_image.src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
base_image.onload = function(){
context.drawImage(base_image, 0, 0);
}
}
const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];
document.write('<br>');
document.write(base64Canvas);
</script>
</body>
</html>
I the code above it does not matter what picture to use. The base64 data is same or every one. Any help?
you should capture the image after it has been loaded and drawn. this is asynchronous action so:
Update: please use an image locally or from an origin that allows CORS.
<!DOCTYPE html>
<html>
<body>
<canvas id="viewport" style="border:1px solid #d3d3d3;"></canvas>
<script>
var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');
make_base();
function make_base() {
base_image = new Image();
base_image.onload = function() {
context.drawImage(base_image, 0, 0);
const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];
console.log(base64Canvas);
}
base_image.crossOrigin = "anonymous"
base_image.src = 'https://picsum.photos/200';
}
</script>
</body>
</html>

Why doesn't my image draw in Canvas ? No error in my code

I got this sample of code which i was working on it, i got a trouble with because my image angular doesn't appear on the web browser, i can't understand what's my mistake, thanks in advance for your help.
<html>
<script>
var canvas,context;
function init(){
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
monImg = new Image();
monImg.src="img/angular.png";
context.drawImage(monImg,300,300);
}
window.onload=init();
</script>
<body>
<canvas id="canvas" width="1920" height="1080"></canvas>
</body>
See this question.
You have to wait for the image to load before you do anything with it. The easiest way is:
monImg = new Image();
monImg.onLoad = function() {
context.drawImage(monImg, 300, 300);
}
monImg.src = "img/angular.png";
You need to add a handler for the Image onload where you call drawImage() such as:
<html>
<body>
<canvas id="canvas" width="1920" height="1080"></canvas>
</body>
<script>
var canvas,context;
function init(){
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
monImg = new Image();
monImg.src="img/angular.png";
monImg.onload = function() {
context.drawImage(monImg,300,300);
}
}
window.onload=init();
</script>
</html>

Draw Image on canvas on button click not working

I am trying to run this code but on click nothing happens.
I think the main problem is the image loading, because when I try
to draw the image that is loaded from an tag it works.
<html>
<body>
<canvas id="myCanvas" width="445" height="312"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<p><button onclick="myCanvas()">Try it</button></p>
<script>
function myCanvas() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image();
img.src = "~/Images/my-meme.jpg";
ctx.drawImage(img, 0, 0, img.width, img.height);
}
</script>
</body>
</html>
You'll need to wait for the image to load before using it. For example,
var img = new Image(); // Create new img element
img.addEventListener("load", function() {
// execute drawImage statements here
}, false);
img.src = 'myImage.png'; // Set source path
See https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images

Loading image from localStorage to canvas works only every second refresh?

I have a little canvas where random rectangles are drawn every time you click on it. On every new rectangle added, the whole canvas is saved to localStorage.
When the webpage is refreshed the last saved image from localStorage is loaded.
PROBLEM:
I have to refresh twice to get the last image/capture. Rrefreshing once gives me only a blank canvas. Why is this?
Index.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="./script.js"></script>
</head>
<body>
<canvas onclick="draw(this, event);" id="drawarea" height="240" width="320" style="border:1px solid black;">
</canvas>
</body>
</html>
script.js:
"use strict;"
window.onload=function(){
c=document.getElementById("drawarea");
if (c) initCanvas(c);
};
function initCanvas(canvas){
// Load last canvas
loadLastCanvas(canvas);
}
function draw(canvas, event){
// Draw at random place
ctx=c.getContext("2d");
ctx.fillStyle="#ff0000";
ctx.beginPath();
ctx.fillRect (250*Math.random()+1, 220*Math.random()+1, 40, 30);
ctx.closePath();
ctx.fill();
// Save canvas
saveCanvas(canvas);
}
function saveCanvas(c){
localStorage['lastImgURI']=c.toDataURL("image/png");
}
function loadLastCanvas(c){
if (!localStorage['lastImgURI']) return;
img = new Image();
img.src= localStorage['lastImgURI'];
ctx=c.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
}
The problem is that img.src = "" is an asynchronous call. So you have to add a callback to the onload event. See html5canvastutorials.com for more information.
function loadLastCanvas(c){
if (!localStorage['lastImgURI']) return;
img = new Image();
img.onload = function() {
ctx=c.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
};
img.src= localStorage['lastImgURI'];
}

HTML Canvas image to Base64 problem

I'm having a problem with retrieving the base64 version of an image displayed on a canvas. I've looked at the other questions but none of the solutions including canvas2image seem to work.
Here's my code:
<!DOCTYPE>
<html>
<head>
<style>#canvas {cursor: pointer;}</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
var can = document.getElementById('canvas');
var ctx = can.getContext('2d');
var img = new Image();
img.onload = function(){
can.width = img.width;
can.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
}
img.src = 'http://sstatic.net/stackoverflow/img/newsletter-ad.png';
can.onclick = function() {
ctx.translate(img.width-1, img.height-1);
ctx.rotate(Math.PI);
ctx.drawImage(img, 0, 0, img.width, img.height);
};
document.write(can.toDataURL()); //isn't writing the correct base64 image
</script>
</body>
</html>
Here's the test link: http://jsfiddle.net/mrchief/hgTdM/1/ thanks, Mrchief
What I need is the correct base64 output of the image in the canvas.
The problem is that it won't output the correct base64 version of the image.. But as you can see, the image inside the canvas is displayed without any problems.
I've tested it on chrome & firefox
Thanks very much..
Your document.write() call occurs immediately upon page load, before your img is loaded and drawn and before your onclick handler can ever run. You need to wait to generate the data URI until after everything has finished happening to the canvas.
Ignoring the onclick, here's something that writes out the data url after the image has loaded and been drawn to the canvas in a rotated fashion:
<!DOCTYPE html>
<html><head>
<title>Rotated Image Data URL</title>
<style type="text/css" media="screen">
canvas, textarea { display:block }
</style>
</head><body>
<canvas id="canvas"></canvas>
<textarea id="data" rows="20" cols="80"></textarea>
<img id="echo">
<script type="text/javascript">
var can = document.getElementById('canvas');
var ctx = can.getContext('2d');
var img = new Image();
img.onload = function(){
can.width = img.width;
can.height = img.height;
ctx.translate(img.width-1, img.height-1);
ctx.rotate(Math.PI);
ctx.drawImage(img, 0, 0, img.width, img.height);
var url = document.getElementById('data').value = can.toDataURL();
document.getElementById('echo').src = url;
}
img.src = 'gkhead.jpg';
</script>
</body></html>
You can see this demo in action here: http://phrogz.net/tmp/upside-down-image-url.html
Note that the image you load must be on the same domain as your script, or else you will not be allowed to create the data URL.

Categories