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);
}
}
...
Related
I'm trying to create a canvas where I have an image as a background that repeats horizontally and adapts the height automatically.
I've managed to repeat the background image following the x-axis but I'm unable to make the height responsive.
This is my code so far:
const cvs = document.getElementById("canvas");
const ctx = cvs.getContext("2d");
const bg = new Image();
bg.src = "http://lorempixel.com/100/100";
const draw = () => {
const ptrn = ctx.createPattern(bg, "repeat-x");
ctx.fillStyle = ptrn;
ctx.fillRect(0, 0, canvas.width, canvas.height);
requestAnimationFrame(draw);
};
draw();
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<canvas id="canvas" width="1000" height="200"></canvas>
<script src="index.js"></script>
</body>
</html>
TLDR: I would like to be able to have an image within my canvas that repeats horizontally and its height is responsive.
Thanks in advance.
Hopefully the explanation in the comments answers your question. Feel free to ask for clarification.
const cvs = document.getElementById("canvas");
const ctx = cvs.getContext("2d");
// First stretch the canvas so we can get
// the full size of teh browser window
cvs.style.height = '100vh';
cvs.style.width = '100vw';
// Now adjust actual canvas size to match
const {width, height} = cvs.getBoundingClientRect();
cvs.height = height;
cvs.width = width;
const bg = new Image();
// Should always wait for onload
// before drawing to prevent race condition.
bg.onload = ()=>{
var x=0;
while(x < cvs.width){
ctx.drawImage(bg, x, 0, 100, cvs.height);
x += bg.width;
}
// draw the image a bunch of times
// var x=0, y=0;
// while(x < cvs.width && y < cvs.height){
// ctx.drawImage(bg, x, y);
// x += bg.width;
// if(x > cvs.width){
// x = 0;
// y += bg.height;
// }
// }
};
bg.src = "http://lorempixel.com/100/100";
<canvas id="canvas"></canvas>
<script src="index.js"></script>
If I got it right you want to fill the height and repeat horizontally, is that correct?
const cvs = document.getElementById("canvas");
const ctx = cvs.getContext("2d");
var bg = new Image();
bg.src = "http://lorempixel.com/100/100";
var tempCanvas = document.createElement("canvas"),
tCtx = tempCanvas.getContext("2d");
var imgWidth = 200;
var imgHeight = 200;
const draw = () => {
tempCanvas.width = imgWidth;
tempCanvas.height = imgHeight;
tCtx.drawImage(bg, 0, 0, 100, 100, 0, 0, imgWidth, imgHeight);
const ptrn = ctx.createPattern(tempCanvas , "repeat-x");
ctx.fillStyle = ptrn;
ctx.fillRect(0, 0, canvas.width, canvas.height);
requestAnimationFrame(draw);
};
bg.onload = () => {
draw();
}
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<canvas id="canvas" width="1000" height="200"></canvas>
<script src="index.js"></script>
</body>
</html>
try setting up the image size to match the canvas size just like that:
bg.src = "http://lorempixel.com/200/200";
Cheers! :)
I am trying to generate a PDF document from a HTML document sing an input and a pre loaded image in my javascript code, here are the codes:
<html>
<head>
<title>
Generar pdf
</title>
</head>
<body>
<input type = "text" id = "jjj">
<button id="button" onclick="generar();"></button>
<script src = "jsPDF-1.3.2/dist/jspdf.debug.js"></script>
<script src = "pdf.js"></script>
</body>
</html>
Javascript
var input = document.getElementById('jjj');
var pdf = new jsPDF();
function generar(){
var texto = input.value;
var imgData = 'https://docs.gimp.org/es/images/tutorials/quickie-jpeg-
100.jpg';
pdf.addImage(imgData, 'JPG', 15, 40, 180, 160);
pdf.text(30, 30, texto);
pdf.save('my_pdf.pdf');
}
And it won't work. It worked with jsut the text, but not the Image. Anyone help, would be very appreciated.
you cannot use direct image url. you need to convert image to base64 and then add it in pdf. Also, using external image will generate error in Chrome / Firefox due to Cross origin request.
Below is the complete code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type = "text" id = "jjj">
<button id="button" onclick="genratePDF();"></button>
<script src = "jspdf.debug.js"></script>
<script src = "jspdf.min.js"></script>
<script>
var input = document.getElementById('jjj');
// var imgData = 'https://docs.gimp.org/es/images/tutorials/quickie-jpeg-100.jpg';
var imgData = 'testimg.jpg';
function genratePDF() {
getDataUri(imgData, function (dataUri) {
generar(dataUri);
});
}
function getDataUri(url, cb)
{
var image = new Image();
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
//next three lines for white background in case png has a transparent background
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#fff'; /// set white fill style
ctx.fillRect(0, 0, canvas.width, canvas.height);
canvas.getContext('2d').drawImage(this, 0, 0);
cb(canvas.toDataURL('image/jpeg'));
};
image.src = url;
}
function generar(img) {
var texto = input.value;
var pdf = new jsPDF();
pdf.addImage(img, 'JPG', 15, 40, 100, 100);
pdf.text(30, 30, texto);
pdf.save('my_pdf.pdf');
}
</script>
</body>
</html>
Main Changes are getDataUri() ; this function generates base64 image of your provided image. And then in Callback it triggers the generar() to generate PDF
function getDataUri(url, cb)
{
var image = new Image();
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
//next three lines for white background in case png has a transparent background
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#fff'; /// set white fill style
ctx.fillRect(0, 0, canvas.width, canvas.height);
canvas.getContext('2d').drawImage(this, 0, 0);
cb(canvas.toDataURL('image/jpeg'));
};
image.src = url;
}
this SO question helps me in this solution Convert a image url to pdf using jspdf
For my website, I need to redraw an image from server which is continuously updating. I found the solution and tried but it still does not auto refresh. I also tried adding a dummy string to my image(local0.jpg) so that the browser does not use cached image but no success. What am I doing wrong?
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<canvas id="canvas" width="400" height="400"> </canvas>
<script>
var imageObj=new Image();
imageObj.src="local0.jpg?dummy=8484744"
imageObj.onload=function()
{
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.drawImage(imageObj,0, 0,canvas.width,canvas.height);
setTimeout(timedRefresh,1000);
}
function timedRefresh()
{
imageObj.src = "local0.jpg?dummy=8484749"
}
</script>
</body>
</html>
Try the following code
var imageObj = new Image();
imageObj.onload = function() {
drawOnCanvas();
setTimeout(timedRefresh, 1000);
}
// set src AFTER assigning load
imageObj.src = "local0.jpg?dummy=" + Math.random();
function timedRefresh() {
imageObj.src = "local0.jpg?dummy=" + Math.random();
//drawOnCanvas(); //flicker was due this line as it try to draw image load so i commented it... now it should work...
}
function drawOnCanvas() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(imageObj, 0, 0, canvas.width, canvas.height);
}
your function timedRefresh add random values to image
function timedRefresh()
{
imageObj.src = "local0.jpg?dummy=" + Math.floor((Math.random() * 10000) + 1);
}
Why does nothing show up on the canvas? The picture is in the same folder as the code, I've tried to directly copy some code, and just change the sources, it still doesn't work. That leads me to believe, that it is not a fault in the actual way I draw the picture, but in the way I load the canvas?
I can add other stuff to the canvas, just not pictures.
<!DOCTYPE html>
<head></head>
<body>
<script>
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.height = 500;
canvas.width = 800;
document.body.appendChild(canvas);
var imag = new Image();
imag.onload = function() {
context.drawImage(imageObj, 0, 0);
};
imag.src = "underwater.png";
</script>
</body>
You most likely copied this code from somewhere and forgot to change the image object name
<!DOCTYPE html>
<head></head>
<body>
<script>
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.height = 500;
canvas.width = 800;
document.body.appendChild(canvas);
var imag = new Image();
imag.onload = function() {
context.drawImage(imag, 0, 0);
};
imag.src = "underwater.png";
</script>
</body>
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