Canvas drawImage is Not Working - javascript

This picture will not draw to the canvas. It is being loaded and I see it when body.appendChild(img); is called. Does anyone had an idea why it is not showing in canvas? I'm following the code example from the html5 course on udacity. Thank you for any help!
<!DOCTYPE html>
<html>
<head>
<title>First Game</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css" rel="stylesheet" href="TestCanvasCSS.css"/>
</head>
<body id="body">
<script>
var canvas;
var ctx = null;
var img = null;
var body = null;
setup = function() {
body = document.getElementById("body");
canvas = document.createElement("canvas");
ctx = canvas.getContext('2d');
//canvas.setAttribute("class","canvasMain");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
body.appendChild(canvas);
img = new Image();
img.onload = onImageLoad();
img.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
};
onImageLoad = function() {
console.log("Image has loaded");
body.appendChild(img);
ctx.drawImage(img, 0, 0);
};
setup();
</script>
<!-- <script type="text/javascript" src="TestCanvas.js"> </script> -->
</body>
</html>

img.onload = onImageLoad;
not onImageLoad(); you're executing the function if you include the parenthesis

Related

Dynamically take Width and height of canvas image and also create another canvas using javascript on one page

I am creating a canvas using javascript with a dynamic image. Now I want to take canvas's height and width dynamically depending on the image. And as well as create another canvas on same page. Here I am attaching my code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
var _puzzleWidth = 640;
var _puzzleHeight = 480;
var _stage;
function init(){
var canvas = document.createElement('canvas');
canvas.id = "CursorLayer";
//canvas.width = _puzzleWidth;
//canvas.height = _puzzleHeight;
_stage = canvas.getContext('2d');
canvas.style.border = "1px solid";
//draw();
var img = new Image();
img.onload = function(){
_stage.drawImage(img, 0, 0);
}
img.src = "http://lorempixel.com/output/animals-q-g-640-480-3.jpg";
var body = document.getElementsByTagName("body")[0];
body.appendChild(canvas);
}
</script>
</head>
<body onload="init();"></body>
</html>
Thanks in advance.
Try this below code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var _puzzleWidth = 640;
var _puzzleHeight = 480;
var _stage;
var _stage2;
function init(){
var canvas2 = document.createElement('canvas');
canvas2.id = "CursorLayer2";
var canvas = document.createElement('canvas');
canvas.id = "CursorLayer";
_stage = canvas.getContext('2d');
canvas.style.border = "1px solid";
_stage2 = canvas2.getContext('2d');
canvas2.style.border = "1px solid";
var img = new Image();
var img1=new Image();
img.onload = function(){
canvas.width = this.width;
canvas.height = this.height;
_stage.drawImage(img, 0, 0);
}
img1.onload = function(){
canvas2.width = this.width;
canvas2.height = this.height;
_stage2.drawImage(img1,0,0);
}
img.src = "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTfSV9AGQi9c48oRysYiuSs9Bs4J3B2p4R3eh-z1hsS-Z01HD17";
img1.src = "http://lorempixel.com/output/animals-q-g-640-480-3.jpg";
var body = document.getElementsByTagName("body")[0];
body.appendChild(canvas);
var body1 = document.getElementsByTagName("body")[0];
body1.appendChild(canvas2);
}
</script>
</head>
<body onload="init();"></body>
</html>

simple J.S. mistake (without error log as it should be)

Hi everyone and thanks for trying to help me ..
I'm trying to create a tiny car game in javaScript, but i actually can't print an image ...
Here's my JS code :
// Parametters
const canvasWidth = 500;
const canvasHeight = 500;
const carLength = 60;
const carWidth = 30;
const canvas = document.getElementById('canvas');
canvas.width = canvasWidth;
canvas.height = canvasHeight;
const context = canvas.getContext('2d');
drawAll();
function drawAll() {
console.log('draw canvas background');
context.fillStyle = 'green';
context.fillRect(0, 0, canvasWidth, canvasHeight);
drawCar();
}
function drawCar() {
let image = new Image();
image.src = 'assets/images/car_orange.png';
context.drawImage(image, 200, 200, carLength, carWidth);
}
and here's the html :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="assets/images/pageIcon/pageIcon.ico" type="image/x-icon" />
<title>CrossingCars</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="drinving_environment.js"></script>
</body>
</html>
the mistake is that my code don't print the image as drawCar() function should do, but if I type each line of code separately in my console it works ...
before console use
after console use
Because your image content isn't loaded yet. You should wait until your image is loaded.
Please refer to this answer here
This issue is always happening on canvas.
...
function drawCar() {
let image = new Image();
image.src = 'assets/images/car_orange.png';
image.onload = function() {
context.drawImage(image, 200, 200, carLength, carWidth);
}
}
...

How do I rotate the entire canvas and an image drawn into the canvas at the same time?

First, upload a tiny image that is wider than it is tall using the following code.
//<![CDATA[
/* js/external.js */
var doc, M, I;
addEventListener('load', function(){
doc = document;
M = function(tag){
return doc.createElement(tag);
}
I = function(id){
return doc.getElementById(id);
}
var canvas = I('canvas'), ctx;
I('upload').onchange = function(){
var files = this.files, file, fr, img;
if(files.length){
file = files[0]; fr = new FileReader; img = M('img');
fr.onload = function(){
img.onload = function(){
canvas.width = this.width; canvas.height = this.height;
ctx = canvas.getContext('2d'); ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
}
img.src = this.result;
}
fr.readAsDataURL(file);
}
}
});
//]]>
/* css/external.css */
*{
float:left; clear:left;
}
#canvas{
margin-top:10px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>canvas rotate</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='js/external.js'></script>
</head>
<body>
<input id='upload' type='file' accept='image/*' />
<canvas id='canvas' width='0' height='0'></canvas>
</body>
</html>
You can see that the image displays in the canvas correctly. That is not my problem, though. I'm really trying to rotate the entire canvas dimensions along with the canvas contents at the same time. If it was a square it would be no problem because I could take half of the height and the width like: ctx.save(); cxt.translate(halfImageWidth, halfImageHeight); ctx.rotate(Math.PI*90/180); ctx.translate(-halfImageWidth, -halfImageHeight); ctx.drawImage(imageContext, 0, 0, imageWidth, imageHeight);.
Here is what I thought would work, but does not:
//<![CDATA[
/* js/external.js */
var doc, M, I;
addEventListener('load', function(){
doc = document;
M = function(tag){
return doc.createElement(tag);
}
I = function(id){
return doc.getElementById(id);
}
var canvas = I('canvas'), ctx;
I('upload').onchange = function(){
var files = this.files, file, fr, img;
if(files.length){
file = files[0]; fr = new FileReader; img = M('img');
fr.onload = function(){
img.onload = function(){
canvas.width = this.height; canvas.height = this.width;
ctx = canvas.getContext('2d'); ctx.save(); ctx.rotate(Math.PI*90/180);
ctx.translate(-canvas.width, 0); ctx.drawImage(this, 0, 0, canvas.width, canvas.height); ctx.restore();
}
img.src = this.result;
}
fr.readAsDataURL(file);
}
}
});
//]]>
/* css/external.css */
*{
float:left; clear:left;
}
#canvas{
margin-top:10px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>canvas rotate</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='js/external.js'></script>
</head>
<body>
<input id='upload' type='file' accept='image/*' />
<canvas id='canvas' width='0' height='0'></canvas>
</body>
</html>
I figured that by not translating before rotation, my origin is top left corner, so I should just be able to set negative origin after rotation, but that doesn't work. If someone could show and explain how to do this correctly I would be most appreciated.
PS
I already thought about a CSS rotation, but since I'm really using the data this won't be a solution for me.
If as you stated, you only need to rotate by 90deg, then it's quite simple.
Your image's width will become your canvas' height, and its height will become the canvas' width.
From there you just have to apply the usual
translate(target-center-x, target-center-y)
rotate(angle)
drawImage(img, -transform-origin, -transform-origin)
fileinput.onchange = e => {
const img = new Image();
img.onload = e => draw(img);
img.src = URL.createObjectURL(fileinput.files[0]);
};
function draw(img) {
const ctx = canvas.getContext('2d');
canvas.width = img.height;
canvas.height = img.width;
// move to center of the canvas
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(Math.PI / 2);
// set the transform origin at center of the image
ctx.drawImage(img, -img.width / 2, -img.height / 2);
}
<input type="file" id="fileinput">
<canvas id="canvas"></canvas>

Javascript Pdfjs Canvas to Img

I've a problem to convert canvas to img..
What's the best approach to use toDataURL() and insert it in img src?
when I launch the script it gives me the correct canvas but the img is blank..
this is my code:
<!DOCTYPE HTML>
<html>
<head>
<script type='text/javascript' src='//code.jquery.com/jquery-2.2.3.js'></script>
<script type="text/javascript" src="https://raw.github.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
</head>
<body>
<div id='anteprima' ></div>
<div id='anteprima_img' ></div>
<script type="text/javascript">
var file = 'http://www.businessmodelgeneration.com/downloads/businessmodelgeneration_preview.pdf';
pdftoimg(file, 1, 0.5, 'anteprima');
function pdftoimg(file, num, scale2, idd) {
PDFJS.disableWorker = true;
PDFJS.getDocument(file).then(function(pdf) {
pdf.getPage(num).then(function(page) {
var canvas = document.createElement('canvas');
canvas.id = 'pag' + num;
canvas.className = 'grande';
canvasContainer = document.getElementById(idd);
var context = canvas.getContext('2d');
var viewport = page.getViewport(scale2);
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
canvasContainer.appendChild(canvas);
var dataUrl = canvas.toDataURL();
image = document.createElement('img');
image.src = dataUrl;
$('#anteprima_img').html(image);
});
});
};
</script>
</body>
</html>
Your code is perfectly fine, you need to just wait for render canvas before converting it to data URL.
page.render(renderContext).then(function(){
// code for converting data url
});
<!DOCTYPE HTML>
<html>
<head>
<script type='text/javascript' src='//code.jquery.com/jquery-2.2.3.js'></script>
<script type="text/javascript" src="https://raw.github.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
</head>
<body>
<div id='anteprima' ></div>
<div id='anteprima_img' ></div>
<script type="text/javascript">
var file = 'http://www.businessmodelgeneration.com/downloads/businessmodelgeneration_preview.pdf';
pdftoimg(file, 1, 0.5, 'anteprima');
function pdftoimg(file, num, scale2, idd) {
PDFJS.disableWorker = true;
PDFJS.getDocument(file).then(function(pdf) {
pdf.getPage(num).then(function(page) {
var canvas = document.createElement('canvas');
canvas.id = 'pag' + num;
canvas.className = 'grande';
canvasContainer = document.getElementById(idd);
var context = canvas.getContext('2d');
var viewport = page.getViewport(scale2);
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext).then(function(){
canvasContainer.appendChild(canvas);
var dataUrl = canvas.toDataURL();
image = document.createElement('img');
image.src = dataUrl;
$('#anteprima_img').html(image);
});
});
});
};
</script>
</body>
</html>

Canvas Image Draw don't work in all Browser

I have this simple code for draw an image in a canvas but it's work only in Firefox
this is the code:
<!DOCTYPE html>
<html>
<head>
<title>CANVAS</title>
</head>
<body>
<canvas id="smallImage" width="600" height="600"></canvas>
<script>
var imgid = document.getElementById('smallImage');
var ctx = imgid.getContext('2d');
var img = new Image();
var immmagine = "flowers.jpg";
img.src = immmagine;
ctx.drawImage(img,0,0);
</script>
</body>
</html>
You need to use the onload event.
img.onload = function() {
ctx.drawImage(img,0,0);
}
You need to listen the onload event on your image :
var imgid = document.getElementById('smallImage');
var ctx = imgid.getContext('2d');
var img = new Image();
var immmagine = "flowers.jpg";
img.src = immmagine;
img.onload = function ()
{
ctx.drawImage(img,0,0);
}

Categories