why my page has a lot of empty space between buttons and canvas. when I upload some image
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>uploader</TITLE>
</HEAD>
<body>
<input type="file" name="img" id="uploadimage" size="1">
<a id="downloadLnk" download="img.jpg">download</a>
</p>
</td>
<script>
function draw() { //upload
var ctx = document.getElementById('canvas').getContext('2d'),
img = new Image(),
f = document.getElementById("uploadimage").files[0],
url = window.zURL || window.URL,
src = url.createObjectURL(f);
img.src = src;
img.onload = function() {
var parkBg = new Image(600, 500);
document.body.appendChild(parkBg);
parkBg.src = src;
}
}
function download() { //upload
var dt = canvas.toDataURL('image/jpeg');
this.href = dt;
};
downloadLnk.addEventListener('click', download, false);
document.getElementById("uploadimage").addEventListener("change", draw, false)
</script>
<canvas id="canvas"></canvas>
</body>
</html>
The empty space you are seeing is in fact canvas element - without CSS styling it is invisible.
You are not displaying image on canvas - You are adding image element to the document and in it displaying uploaded image.
I suspect You need to display image on canvas.
See my example that accomplishes exactly that: https://jsfiddle.net/hxfp39wo/1/
Related
Please suggest some library for Image processing.
We tried to draw image to canvas and then to download the image of required size, but not achievable.
We like to use this mechanism to reduce image processing in back-end server
Below is the code we tried
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Image Resize</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<form>
<input id="filez" type="file" value="img">
<div id="parentDiv"></div>
</form>
</body>
<script type="text/javascript">
$(document).ready(function(){
function ImageResizeObject(parentElement,fileElement,objz){
this.parentElement = $(parentElement);
this.fileElement = document.getElementById(fileElement);
this.objz = objz;
this.imageFile = this.fileElement.files[0];
this.parentElement.empty();
for(var i=0;i<this.objz.length;i++){
var parentDiv = $("<div></div>");
parentDiv.attr("id","parentDiv parentDiv"+i);
var canvas = $("<canvas id='parentDivCanvas"+i+"'></canvas>");
canvas.css({"height":objz[i].height,"width":this.objz[i].width});
parentDiv.append(canvas);
this.parentElement.append(parentDiv);
var ctx = canvas[0].getContext('2d');
var img = new Image();
img.src =URL.createObjectURL(this.imageFile);
ctx.drawImage(img,0,0,img.width,img.height,0, 0,canvas.width(),canvas.height());
}
}
$("#filez").on('change', function(){
console.log("file uploaded");
FileUpload = new ImageResizeObject("#parentDiv","filez",[{"height":"410","width":"410"},{"height":"205","width":"205"}]);
});
});
</script>
</html>
On Stackoverflow, we don't make library recommendations, but...
You can use html5 canvas to resize images.
Create a canvas element
Size it to your desired scaled size
Draw the image onto the canvas with scaling to the desired size
Create a resized imageObject using the canvas as the image.src
Here's example code and a Demo:
var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/marioRunningRight1.png";
function start(){
resizeImg(img,0.50);
resizeImg(img,2);
}
function resizeImg(img,scaleFactor){
var c=document.createElement('canvas');
var ctx=c.getContext('2d');
var iw=img.width;
var ih=img.height;
c.width=iw*scaleFactor;
c.height=ih*scaleFactor;
ctx.drawImage(img,0,0,iw*scaleFactor,ih*scaleFactor);
var scaledImg=new Image();
scaledImg.onload=function(){
// scaledImg is a scaled imageObject for upload/download
// For testing, just append it to the DOM
document.body.appendChild(scaledImg);
}
scaledImg.src=c.toDataURL();
}
<h4>Original image</h4>
<img src='https://dl.dropboxusercontent.com/u/139992952/multple/marioRunningRight1.png' crossOrigin='anonymous'>
<br>
<h4>Resized images at 50% and at 200%</h4>
I need to add text to an already uploaded image and then upload the new image with the text back onto the server.
I'd like to use an image which is already on the server, which means that I have a variable $image_location linking directly to the image already set.
I found some code on StackOverflow which enables putting text on the image which you upload through the upload form.
My question is how would I change it so that instead of uploading the image, I could use the image already on my server.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
var
maxSize=600, // Max width or height of the image
font='italic small-caps bold 40px/50px arial', // font style
fontColor='white', // font color
textX=50, // text x position
textY=50, // text y position
h=function(e){
var fr=new FileReader();
fr.onload=function(e){
var img=new Image();
img.onload=function(){
var r=maxSize/Math.max(this.width,this.height),
w=Math.round(this.width*r),
h=Math.round(this.height*r),
c=document.createElement("canvas"),cc=c.getContext("2d");
c.width=w;c.height=h;
cc.drawImage(this,0,0,w,h);
cc.font=font;
cc.fillStyle=fontColor;
cc.fillText(document.getElementById('t').value,textX,textY);
this.src=c.toDataURL();
document.body.appendChild(this);
}
img.src=e.target.result;
}
fr.readAsDataURL(e.target.files[0]);
}
window.onload=function(){
document.getElementById('f').addEventListener('change',h,false);
}
</script>
</head>
<body>
1.write text
<input type="text" id="t">
2.add image
<input type="file" id="f">
</body>
</html>
You can load an image to the canvas like so:
var img = new Image();
img.onload = function(){
c.width = img.width;
c.height = img.height;
cc.drawImage(img, 0, 0, img.width, img.height);
}
img.src = '/path/to/image.jpg';
so it looks like the only thing you'd need to change is the img.src variable
The code runs with no bugs, but a problem I am having is because the ".onLoad" function makes it display after the text has already been displayed on the screen. The problem I am facing is that I would like if the text (Loading graphics and loading variables) displayed over the image.
The code is here:
<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml1-transitional.dtd">
<html>
<body>
<canvas id="ctx" width="800" height="500" style="border:1px solid #d3d3d3;"></canvas>
<script>
var ctx = document.getElementById("ctx").getContext("2d");
var canvas = document.getElementById('ctx');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj,0,0);
};
imageObj.src = 'img/startscreen.jpg';
ctx.fillText('Loading variables.',50,50);
character=new Object();
character.hp=1;
character.name=null;
ctx.fillText('Loading graphics..',50,100);
</script>
</body>
</html>
I would layer the background image on its own canvas positioned behind the text layer. Then you can clear and update the text layer without having to re-draw the background image.
#background,#overlay {
position: absolute;
}
<canvas id="background"></canvas>
<canvas id="overlay"></canvas>
var can = document.getElementById('overlay'),
bg_can = document.getElementById('background'),
height = can.height = bg_can.height = 500,
width = can.width = bg_can.width = 500,
ctx = can.getContext('2d'),
bctx = bg_can.getContext('2d');
var img = new Image();
img.src = ' ... ';
img.onload = init;
function init() {
// draw the background
bctx.drawImage(this, 0, 0);
// draw your initial text
updateText('hello world');
// other stuff that is going to take time
updateText('done');
}
function updateText(msg) {
ctx.clearRect(0, 0, width, height);
ctx.fillText(msg, 50, 100);
}
This isn't very well thought out (my code example) for re-use purposes.. but I don't know much about your other needs :) hope this helps.
If you want to overlay String on image, why don you use image as backGround imange and place text over it??
Css
try in css
#ctx{
background-image:url('img/startscreen.jpg');}
remove image source in script or insert css in script itself
Css in scripts
ctx.style.backgroundImage=url('img/startscreen.jpg');
I called the function for the text to be displayed after the background has:
imageObj.src = 'img/startscreen.jpg';
imageObj.onload = function(){
context.drawImage(imageObj,0,0);
init()
};
function init(){
ctx.fillText('Loading variables.',50,50);
character=new Object();
character.hp=1;
character.name=null;
ctx.fillText('Loading graphics..',50,100);
}
I'm trying to create a web design custom made dress. I made it with easel.js. I have a problem when I upload images into the clothes that are on the canvas when the initial functions, image shirt has disappeared ("upload / men_shirt_front.png").
function init() {
canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
var ctx = canvas.getContext("2d");
// Enable touch support
if (createjs.Touch.isSupported()) { createjs.Touch.enable(stage); }
// create amd draw the branding image for the qr-code
var Shirt = new Image();
Shirt.addEventListener('load', function () {
ctx.drawImage(this, 10, 10, 275, 275);
},false);
Shirt.src = "upload/men_shirt_front.png";
}
I know that the real problem is in
displayPicture = function (imgPath) {
var image = new Image();
image.onload = function () {
// Create a Bitmap from the loaded image
var img = new createjs.Bitmap(event.target)
// scale it
img.scaleX = img.scaleY = 0.5;
/// Add to display list
stage.addChild(img);
//Enable Drag'n'Drop
enableDrag(img);
// Render Stage
stage.update();
}
// Load the image
image.src = imgPath;
}
I have tried many many ways to change it but I can not. how to upload a new image in canvas without eliminating existing image in initial function?
below is the full 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">
<head>
<title>Upload and display images on HTML5 Canvas</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
<script src="easeljs-0.5.0.min.js"></script>
<script src="jquery-1.8.2.js"></script>
<script type="text/javascript" src="libs/upclick-min.js"></script>
<script src="libs/export_canvas/base64.js" type="text/javascript"></script>
<script src="libs/export_canvas/canvas2image.js" type="text/javascript"></script>
</head>
<script type="text/javascript">
/** Init */
window.onload = init;
function init() {
canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
var ctx = canvas.getContext("2d");
// Enable touch support
if (createjs.Touch.isSupported()) { createjs.Touch.enable(stage); }
// create amd draw the branding image for the qr-code
var Shirt = new Image();
Shirt.addEventListener('load', function () {
ctx.drawImage(this, 10, 10, 275, 275);
},false);
Shirt.src = "upload/men_shirt_front.png";
}
/**Export and save the canvas as PNG */
function exportAndSaveCanvas() {
// Get the canvas screenshot as PNG
var screenshot = Canvas2Image.saveAsPNG(canvas, true);
// This is a little trick to get the SRC attribute from the generated <img> screenshot
canvas.parentNode.appendChild(screenshot);
screenshot.id = "canvasimage";
data = $('#canvasimage').attr('src');
canvas.parentNode.removeChild(screenshot);
// Send the screenshot to PHP to save it on the server
var url = 'upload/export.php';
$.ajax({
type: "POST",
url: url,
dataType: 'text',
data: {
base64data : data
}
});
}
/** Export and display the canvas as PNG in a new window */
function exportAndView() {
var screenshot = Canvas2Image.saveAsPNG(canvas, true);
var win = window.open();
$(win.document.body).html(screenshot );
}
</script>
<body onload="init()">
<div style="position: relative" >
<input type="button" value="View screenshot in a new page" onClick="exportAndView()" >
<input type="button" value="Export and Upload Screenshot" onClick="exportAndSaveCanvas()" >
<input id="uploader" type="button" value="Upload picture from hard disk">
</div>
<canvas width="1000" height="550" id="canvas"></canvas>
<script type="text/javascript">
var canvas;
var stage;
var uploader = document.getElementById('uploader');
/**
* UPLOAD SCRIPT
* This script uses the upclick-min.js library to upload files on a webserver folder
* using a PHP script ("upload/upload.php")
* Project homepage: http://code.google.com/p/upload-at-click/
*/
upclick(
{
element: uploader,
action: 'upload/upload.php',
onstart:
function(filename)
{
//alert('Start upload: '+filename);
},
oncomplete:
function(response_data)
{
// Check upload Status
if (response_data != "FAIL") {
// Draw the picture into Canvas
// "response_data" contains the image file name returned from the PHP script
displayPicture("upload/" + response_data);
}
}
});
/**
* Load and display the uploaded picture on CreateJS Stage
*/
displayPicture = function (imgPath) {
var image = new Image();
image.onload = function () {
// Create a Bitmap from the loaded image
var img = new createjs.Bitmap(event.target)
// scale it
img.scaleX = img.scaleY = 0.5;
/// Add to display list
stage.addChild(img);
//Enable Drag'n'Drop
enableDrag(img);
// Render Stage
stage.update();
}
// Load the image
image.src = imgPath;
}
/**
* Enable drag'n'drop on DisplayObjects
*/
enableDrag = function (item) {
// OnPress event handler
item.onPress = function(evt) {
var offset = { x:item.x-evt.stageX,
y:item.y-evt.stageY};
// Bring to front
stage.addChild(item);
// Mouse Move event handler
evt.onMouseMove = function(ev) {
item.x = ev.stageX+offset.x;
item.y = ev.stageY+offset.y;
stage.update();
}
}
}
</script>
</body>
</html>
It's upload script 'upload/upload.php'
<?php
$tmp_file_name = $_FILES['Filedata']['tmp_name'];
$ok = move_uploaded_file($tmp_file_name, $_FILES['Filedata']['name']);
// This message will be passed to 'oncomplete' function
echo $ok ? $_FILES['Filedata']['name'] : "FAIL";
?>
I have this code im using on my website but the image does not load when page opens, I want the image to load from start up then a simple mouse over to change image and a link when clicked. Im not good at coding so any help would be good.
here is the code im using.
<!doctype html>
<html>
<body>
<head>
<script>
function init() {
setImageOne();
}
function setImageOne() { setImage('http://earthbounds.com/banners/amazing food.jpg'); }
function setImageTwo() { setImage('http://earthbounds.com/banners/amazing food 2.jpg'); }
function setImage(src) {
var canvas = document.getElementById("e");
var context = canvas.getContext("2d");
if (context == null) return;
var img = new Image();
img.src = src;
context.drawImage(img, 0, 0, 322, 200);
}
</script>
</head>
No Canvas Support in Browser
You need to wait for the image to load before you draw it. Also, if your browser doesn't support canvas nothing will help you with this approach.
function setImage(src) {
var canvas = document.getElementById("e");
var context = canvas.getContext("2d");
if (context == null) return;
var img = new Image();
img.onload = function () {
context.drawImage(img, 0, 0, 322, 200);
};
img.src = src;
}
You should wait for the image to load. Thus your code should be (with corrections regarding html markup):
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
</head>
<body>
<canvas id="e" style="width: 100%; height: 100%;"></canvas>
<script>
function init() {
setImageOne();
}
function setImageOne() { setImage('http://earthbounds.com/banners/amazing food.jpg'); }
function setImageTwo() { setImage('http://earthbounds.com/banners/amazing food 2.jpg'); }
function setImage(src) {
var canvas = document.getElementById("e");
var context = canvas.getContext("2d");
if (context == null) return;
var img = new Image;
img.onload = function (){
context.drawImage(img, 10, 10);
};
img.src = src;
}
init();
</script>
</body>
</html>
This only works in browsers that support canvas ex: Chrome(ium)
Also I suggest you read this
Is this the first method you tried? If you are just trying to add an image on a website and a hover over it there is a much simpler way.
First off, instead of using Javascript to create and load an Image, use the HTML <img> tag, example:
<img src="http://earthbounds.com/banners/amazing food.jpg">
Now to add a simple hover image change, this is not the best practice but for an example, and for a single image you can use onmouseover and onmouseout, example:
<img src="http://earthbounds.com/banners/amazing food.jpg" onmouseover="this.src('http://earthbounds.com/banners/amazing food 2.jpg')" onmouseout="this.src('http://earthbounds.com/banners/amazing food.jpg')">
Now to make this image a link to another page, or website you use the <a> tag, example:
<img src="http://earthbounds.com/banners/amazing food.jpg" onmouseover="this.src('http://earthbounds.com/banners/amazing food 2.jpg')" onmouseout="this.src('http://earthbounds.com/banners/amazing food.jpg')">
Hope this helps, and keep looking and learning!