i wrote this code but the browser refuse to display the pipe image from canvas. I need some help please.
var cvs = document.getElementById("canvas");
var ctx = cvs.getContext("2d");
var chickenImage = new Image();
var pipe = new Image();
var jumpSound = new Audio();
chickenImage.src="asset/chicken.png";
pipe.src ="asset/pipe.png";
jumpSound.src ="asset/jump.wav";
function draw(){
ctx.drawImage(pipe,100,0);
}
draw();
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>chicken</title>
</head>
<body>
<canvas id="canvas" width="288" height="512"></canvas>
<script src="main.js"></script>
</body>
</html>
You will need to wait for onload event, for the image to be loaded then you can draw her in the canvas.
pipe.onload = function () {
ctx.drawImage(pipe, 0, 0);
};
pipe.src ="asset/pipe.png";
Or in your code you can use also:
pipe.onload = function () {
draw();
};
pipe.src ="asset/pipe.png";
You need to wait until the image is loaded. The easiest way would be the .onload event which is run, when the image is finished loading and to use it just set it to your draw() function.
var cvs = document.getElementById("canvas");
var ctx = cvs.getContext("2d");
var chickenImage = new Image();
var pipe = new Image();
var jumpSound = new Audio();
//chickenImage.src="asset/chicken.png";
pipe.src = "https://lorempixel.com/g/400/200/?random";
//jumpSound.src ="asset/jump.wav";
function draw() {
ctx.drawImage(pipe, 100, 0);
}
pipe.onload = draw;
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>chicken</title>
</head>
<body>
<canvas id="canvas" width="288" height="512"></canvas>
</body>
</html>
Related
I am currently having issues with displaying images in the HTML canvas. I am still new and I am quite tired so its likely theres somthing stupid I did not do. Heres the code:
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.height = 695;
canvas.width = 1515;
//Images
const BG = new Image();
BG.src = "C:\Users\MSI\Documents\ABGG Remastered\StartImg.png"
ctx.drawImage(BG, 0, 0);
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas"></canvas>
<script src="C:\Users\MSI\Documents\ABGG Remastered\mainScript.js">
</script>
<style>
canvas {
border: 1px solid;
}
</style>
</body>
</html>
Thanks for the help!
Loading an image is not instantly so you need to wait for it to be loaded first which you can do with the onload function of the image
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.height = 695;
canvas.width = 1515;
//Images
const BG = new Image();
BG.src = "https://images3.alphacoders.com/899/thumb-1920-899727.jpg"
BG.onload = () => {ctx.drawImage(BG, 0, 0);}
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas"></canvas>
<script src="C:\Users\MSI\Documents\ABGG Remastered\mainScript.js">
</script>
<style>
canvas {
border: 1px solid;
}
</style>
</body>
</html>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.height = 695;
canvas.width = 1515;
//Images
const BG = new Image();
BG.addEventListener('load', function() {
ctx.drawImage(BG, 20,20);
})
BG.src = "C:\\Users\\dhrum\\Documents\\Projects\\WizemenDesktop\\WizemenDesktop\\Assets\\icon.png"
</script>
I changed to code to this and it works. First of all, I'd recommend using a method to wait for the image to load, and then draw it (slow servers or large files can take a little to load, and hence wont be drawn if not loaded).
Second of all, your issue that that \ escapes the character, and you'd want to do \\, where the first \ will escape the 2nd \ which would make the actual value of the string with only 1 \.
To understand what escaping a character means, you can go here
I am using compressor.js for image compression and watermarking. However, only text based watermark seems to be possible to me. I want to add image (logo) into watermark too.
Any idea how to use image as watermark with compressor.js?
You can do this by using the drew function, like so:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/compressorjs/1.0.7/compressor.min.js"></script>
</head>
<body>
<img id="watermark" src="watermark.png" style="display: none" />
<h3>Input</h3>
<div id="input"><img id="image" src="picture.png" style="max-width:250px"></div>
<h3>Output</h3>
<div id="output"></div>
<script>
window.addEventListener('DOMContentLoaded', function () {
var Compressor = window.Compressor;
var URL = window.URL || window.webkitURL;
var image = document.getElementById('image');
var output = document.getElementById('output');
var watermark = document.getElementById('watermark');
var xhr = new XMLHttpRequest();
xhr.onload = function () {
new Compressor(xhr.response, {
strict: false,
drew: function (context, canvas) {
context.drawImage(
watermark,
0,
0,
watermark.width,
watermark.height,
canvas.width - ((watermark.width / 4) + 10),
canvas.height - ((watermark.height / 4) + 10),
(watermark.width / 4),
(watermark.height / 4))
},
success: function (result) {
var newImage = new Image();
newImage.src = URL.createObjectURL(result);
newImage.style = "max-width:250px";
output.appendChild(newImage);
},
error: function (err) {
window.alert(err.message);
},
});
};
xhr.open('GET', image.src);
xhr.responseType = 'blob';
xhr.send();
});
</script>
</body>
</html>
All of the dividing by 4 is because my watermark image is massive. That's not required.
Here's a screenshot of the before/after:
Alternative Method
Here's an alternative way to add a watermark to an image:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<img id="watermark" src="https://upload.wikimedia.org/wikipedia/en/7/71/Corona_Extra.svg" style="display: none" />
<img id="image" src="https://images.unsplash.com/photo-1665606855702-144fd49af552?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80%20870w" style="display:none">
<canvas id="output"></canvas>
<script>
var imagesLoaded = 0;
var main = document.getElementById("image");
var watermark = document.getElementById("watermark");
function imageHasLoaded() {
imagesLoaded++;
if (imagesLoaded == 2) {
var c = document.getElementById("output");
var ctx = c.getContext("2d");
c.width = main.width;
c.height = main.height;
ctx.drawImage(main,
0, 0,
main.width, main.height,
0, 0,
main.width, main.height);
ctx.drawImage(watermark,
0, 0,
watermark.width, watermark.height,
(main.width - watermark.width) / 2, (main.height - watermark.height),
watermark.width, watermark.height);
}
}
main.load = imageHasLoaded();
watermark.load = imageHasLoaded();
</script>
</body>
</html>
I am trying to get image from external link and add in a document.
Html service work fine. However, document should fill out after onload function.
How can I fix it ?
code.gs
function doGet(e){
var content = HtmlService.createHtmlOutputFromFile('index').getContent();
return HtmlService.createHtmlOutput(content);
}
function im(baseUrl){
var resp = UrlFetchApp.fetch(baseUrl);
var docID = "0000xxxxx1111"
var doc = DocumentApp.openById(docID);
doc.getChild(0).asParagraph().appendInlineImage(resp.getBlob());
return baseUrl;
}
index.html
<!DOCTYPE html>
<head>
<base target="_top">
<script>
window.onload = function() {
var url = "http://xxx.co/image.png"
var canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 100;
document.getElementById('barcode').appendChild(canvas);
var ctx = canvas.getContext('2d');
var image = new Image();
image.src = url;
ctx.drawImage(image, 0, 0);
google.script.run.withSuccessHandler(function(a) {
document.getElementById("imageid").src=a;
}).im(canvas.toDataURL());
}
</script>
</head>
<body>
<img id="imageid" src="" alt="image">
</body>
</html>
There are a few problems with your HTML which is why it probably isn't working. You also had not tagged any elements with the barcode id.
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body id="barcode">
<img id="imageid" src="" alt="image">
</body>
<script>
window.onload = function() {
var url = "http://lorempixel.com/400/200/"
var canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 100;
document.getElementById('barcode').appendChild(canvas);
var ctx = canvas.getContext('2d');
var image = new Image();
image.src = url;
ctx.drawImage(image, 0, 0);
google.script.run.withSuccessHandler(function(a) {
document.getElementById("imageid").src=a;
}).im(canvas.toDataURL());
}
</script>
</html>
I have a problem. I'm using HTML5 and Javascript to draw a box onto a canvas. This box is supposed to move up and down, but after it gets rendered for the first time, it doesn't want to re-render at the new position. This is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="sl" lang="sl">
<head>
<title>Spletna stran Portfolio - Domaca stran</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link rel="stylesheet" href="css/style.css" type="text/css" media="all" />
<script>
var isMoving = true;
var gradienty = 0;
var gradientheight = 100;
var gradientyVel = 1;
var gradientImage = new Image();
gradientImage.src = "grafika/gradient.gif";
function main() {
var c = document.getElementById("menuCanvas");
var ctx = c.getContext("2d");
ctx.drawImage(gradientImage, 0, gradienty);
if(isMoving == true) {
gradienty += gradientyVel;
if((gradienty+gradientheight)==c,height || gradienty<=0) {
gradientyVel *= -1;
}
}
}
function mainLoop() {
setInterval(main(), 10);
}
</script>
</head>
<body onload="mainLoop()">
<canvas id="menuCanvas" width="195" height="400"></canvas>
</body>
</html>
I have no clue why the box isn't moving. It's like after I draw it for the first time it won't draw again the next time. Also, I use mainLoop() function as my main loop. Every 10 miliseconds I basically call the main() function, which does the drawing and the logic.
Any help would be much appreciated. :)
A few coding problems:
You need to give your image time to load, then start the animation
var gradientImage = new Image();
gradientImage.onload=function(){
setInterval(main, 20);
}
gradientImage.src = "house16x16.png";
setInterval takes in a function pointer (no parentheses):
setInterval will fire only as fast as 16ms, so your 10ms value is too small
setInterval(main, 20);
Here's revised code and a Demo: http://jsfiddle.net/m1erickson/U6K9j/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var c=document.getElementById("menuCanvas");
var ctx=c.getContext("2d");
var isMoving = true;
var gradienty = 0;
var gradientheight = 100;
var gradientyVel = 1;
var gradientImage = new Image();
gradientImage.onload=function(){
setInterval(main, 20);
}
gradientImage.src = "house16x16.png";
function main() {
ctx.clearRect(0,0,c.width,c.height);
ctx.drawImage(gradientImage, 0, gradienty);
if(isMoving == true) {
gradienty += gradientyVel;
if((gradienty+gradientheight)==c.height || gradienty<=0) {
gradientyVel *= -1;
}
}
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="menuCanvas" width=300 height=300></canvas>
</body>
</html>
You're calling main and then passing the RESULT to setInterval. Just change
function mainLoop() {
setInterval(main(), 10);
}
to
function mainLoop() {
setInterval(main, 10);
}
That'll get you started, but you'll also need to clear the canvas in between draws. (As you'll notice if you run this)
I want to be able to click on a button on my page and load an image into a canvas at some X,Y coordinates?
The following code is what I have below. I would like the image to be in either image/photo.jpg or in the same directory but preferably in a subdirectory of the main page.
**Question: How to make a JPG show up in a canvas with the click of a button on the web page?
Code:
<!DOCTYPE html>
<html>
<script>
function draw(){
var ctx = document.getElementById("myCanvas").getContext("2d");
var img = new Image():
// img.src = "2c.jpg";
img.src = "/images/2c.jpg";
ctx.drawImage(img,0,0);
}
</script>
<body background="Black">
<div align="center">
<button type="button" onclick="draw()">Show Image on Canvas</button>
<canvas id="myCanvas" width="900" height="400" style="border:2px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
</div>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="20px Arial";
ctx.fillText("Royal Flush $",500,50);
ctx.fillText("Striaght Flush $",500,80);
ctx.fillText("Flush $",500,110);
ctx.fillText("Four of a Kind $",500,140);
ctx.fillText("Full House $",500,170);
ctx.fillText("Three of a Kind $",500,200);
ctx.fillText("Two Pair $",500,230);
ctx.fillText("Pair of ACES $",500,260);
ctx.rect(495,10,270,350);
ctx.stroke();
</script>
</body>
</html>
March 6th, 2014 Code:
How is the following code not working. Do you have to have an ID tag on Canvas. The page will display but for some reason the image will not when the button is clicked. The image is in the same directory that my index.html file is in.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
canvas{
border: 5px solid black;
}
</style>
</html>
<button id="galaxy">Add image #1</button>
<button id="circles">Add image #2</button><span></span>
<canvas width="500" height="500"></canvas>
<script>
var Images = {};
function loadImages(list){
var total = 0;
document.querySelector("span").innerText = "...Loading...";
for(var i = 0; i < list.length; i++){
var img = new Image();
Images[list[i].name] = img;
img.onload = function(){
total++;
if(total == list.length){
document.querySelector("span").innerText = "...Loaded.";
}
};
img.src = list[i].url;
}
}
function drawImage(img){
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(Images[img], 0, 0, 50, 50);
}
loadImages([{
name: "2c.jpg",
url: "mp.jpg"
},{
name: "mp.jpg",
url: "mp.jpg"
}]);
document.querySelector("#galaxy").addEventListener("click", function(){
drawImage("galaxy");
});
document.querySelector("#circles").addEventListener("click", function(){
drawImage("weirdCircles");
});
</script>
</html>
Wait till the image is loaded before drawing:
var img = new Image();
img.onload = function(){ /*or*/ img.addEventListener("load", function(){
ctx.drawImage(img,0,0); ctx.drawImage(img,0,0);
}; };
img.src = "/images/2c.jpg";
Demo: http://jsfiddle.net/DerekL/YcLgw/
If you have more than one image in your game,
It is better to preload all images before it starts.
Preload images: http://jsfiddle.net/DerekL/uCQAH/ (Without jQuery: http://jsfiddle.net/DerekL/Lr9Gb/)
If you are more familiar with OOP: http://jsfiddle.net/DerekL/2F2gu/
function ImageCollection(list, callback){
var total = 0, images = {}; //private :)
for(var i = 0; i < list.length; i++){
var img = new Image();
images[list[i].name] = img;
img.onload = function(){
total++;
if(total == list.length){
callback && callback();
}
};
img.src = list[i].url;
}
this.get = function(name){
return images[name] || (function(){throw "Not exist"})();
};
}
//Create an ImageCollection to load and store my images
var images = new ImageCollection([{
name: "MyImage", url: "//example.com/example.jpg"
}]);
//To pick and draw an image from the collection:
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(images.get("MyImage"), 0, 0);