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>
Related
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 want to create a function which compress the image after selecting and append it to the body.
Here is my code =>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Image Compression</title>
</head>
<body>
<input type="file" accept=".jpg,.jpeg,.png" id="random-img" />
</body>
<script>
const Compress = function (img_obj, quality, output_format) {
var mime_type = output_format;
var cvs = document.createElement("canvas");
img_obj.onload = function () {
cvs.width = img_obj.naturalWidth;
cvs.height = img_obj.naturalHeight;
};
var ctx = cvs.getContext("2d").drawImage(img_obj, 0, 0);
var newImageData = cvs.toDataURL(mime_type, quality / 100);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
return result_image_obj;
};
function getImg() {
const src_obj = document.getElementById("random-img").files[0];
const newImg = new Image();
newImg.src = URL.createObjectURL(src_obj);
const compressed_img = Compress(newImg, 80, src_obj.type);
document.querySelector("body").appendChild(compressed_img);
}
document.querySelector("input").addEventListener("change", getImg);
</script>
</html>
The problem is I am not able to see the image on the screen.Instead I see any empty white box of 300 x 150 size when I open the developer tool and hover over the image element.
Please help! Thankyou!
img_obj.onload() is asynchronous, you can't just immediately return from it.
const Compress = function (img_obj, quality, output_format) {
var mime_type = output_format;
var cvs = document.createElement("canvas");
img_obj.onload = function () {
cvs.width = img_obj.naturalWidth;
cvs.height = img_obj.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(img_obj, 0, 0);
var newImageData = cvs.toDataURL(mime_type, quality / 100);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
document.querySelector("body").appendChild(result_image_obj);
};
};
function getImg() {
const src_obj = document.getElementById("random-img").files[0];
const newImg = new Image();
newImg.src = URL.createObjectURL(src_obj);
const compressed_img = Compress(newImg, 80, src_obj.type);
}
document.querySelector("input").addEventListener("change", getImg);
<input type="file" accept=".jpg,.jpeg,.png" id="random-img" />
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>
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);
I can't draw the image using the function of the class.
I allready tried this.img and var img but they are both not working.
I added an online source of the jquery-libaryto place it online, but on my pc i'm using an offline source that is working!
<!doctype html>
<head>
<link rel="stylesheet" href="js\jquery-ui-1.10.1.custom.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"> </script>
<script type="text/javascript">
var canvas;
var ctx;
var BurgerArray = new Array(50);
function burger()
{
this.x = 10;
this.y = 20;
this.img = new Image();
img.src='Img/Burger1.png';
img.onload = function()
{
}
this.teken = function()
{
ctx.drawImage(img,20,20);
}
}
var b;
$(document).ready(function()
{
canvas =document.getElementById("MyCanvas");
ctx =canvas.getContext("2d");
b = new burger();
b.teken();
});
</script>
<style type="text/css">
#MyCanvas
{
margin:auto;
display:block;
border:dashed;
border-color:#0F0;
}
</style>
</head>
<body style=" width:100%; height:100%;">
<canvas id="MyCanvas" width="1000" height="600"></canvas>
</body>
</html>
When you create a new object, it's scope is different from the global one. Change the implementation to:
function burger(canvas)
{
this.x = 10;
this.y = 20;
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.teken = function() {
this.ctx.drawImage(img,20,20);
};
}
$(document).ready(function() {
var canvas = document.getElementById("MyCanvas");
var b = new burger(canvas);
b.teken();
});