upload a new image in canvas without eliminating existing image - javascript

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";
?>

Related

canvas element has extra wide upper border

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/

Javascript : Upload Image file and resize to different resolution then download

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>

how to load bitmap using easeljs?

I am trying to load bitmap using easeljs but its not working, please help me.
function init() {
canvas = document.getElementById("testCanvas");
context = canvas.getContext("2d");
stage = new createjs.Stage(canvas);
var image = new Image();
image.src = "assets/puli.png";
var container = new createjs.Container();
stage.addChild(container);
bitmap = new createjs.Bitmap(image);
container.addChild(bitmap);
createjs.Ticker.addEventListener("tick", tick);
}
function tick(event) {
if (update) {
update = false; // only update once
stage.update(event);
}
}
You have to load your images using the LoadQueue Class form EaselJs:
take a look at this--> http://www.createjs.com/Docs/PreloadJS/classes/LoadQueue.html
var queue = new createjs.LoadQueue(true);
queue.addEventListener("fileload",onFileLoaded.bind(this));
var manifest = getManifest();
queue.loadManifest(manifest);
onFileLoaded = function(evt)
{
var item = evt.item;
var type = evt.type;
}
getManifest = function()
{
var manifest = [
{src:"/images/yourimage.png", id:"myimage"}
];
return manifest;
}
//create images
var myimage = new createjs.Bitmap(images.myimage);
#CMS is right that preloading the content helps -- the issue you are seeing is likely that the image is not loaded when you update the stage, and it is only updating once.
You can use your approach in the original question, as long as you update the stage once the image is loaded. You can do this simply by waiting for a load event from the image. Something like this:
image.onload = function() {
update = true;
// OR
stage.update();
}
Using PreloadJS is a better approach for a larger app, since it gives you way more control of when assets are loaded, etc -- but its not necessary to get your code working.
I feel your pain.
Try this - I put the addChild and stage update in the onload event.
Works for me.
var stage, rect, img, greenRect;
function init() {
stage = new createjs.Stage("demoCanvas");
rect = new createjs.Shape();
img = new Image();
img.src = 'green.jpg';
img.onload = handleImageLoad;
}
function handleImageLoad(event) {
greenRect = new createjs.Bitmap(img);
stage.addChild(greenRect);
greenRect.x = 100;
greenRect.y = 100;
stage.update();
}
I got this code from YouTube, and it works
<!DOCTYPE html>
<html>
<head>
<script src="easeljs.js"></script> <!==load the EaselJS library==>
<script>
//this sample displays a bitmap file
var stage, img, map; //declare global variables
function init() {
//this function is registered in the html body tag
stage = new createjs.Stage("demoCanvas"); //create a Stage object to work with the canvas element
img = new Image(); //create an Image object, then set its source property
img.src="my_photo.jpg";
img.onload = handleImageLoad //register a handler for the onLoad event
}
function handleImageLoad(event) {
//this function runs when the onload event completes
map = new createjs.Bitmap(img); //create a Bitmap object, then set properties
map.x =50;
map.y =50;
stage.addChild(map); //add the Bitmap object as a child of the stage, then update the stage
stage.update();
}
</script>
</head>
<body onload="init();">
<!==add a canvas tag==>
<canvas id="demoCanvas" width="640" height="480"></canvas>
</body>
</html>
This code works when the PreloadJS library is sourced
<!DOCTYPE html>
<html>
<head>
<script src="EaselJS/lib/easeljs.js"></script> <!==load the EaselJS library==>
<script src="PreloadJS/lib/preloadjs.js"></script> <!==load the PreloadJS library==>
<script>
//this sample displays a bitmap file
var stage; //declare global variables
var img;
var map;
var queue;
function init() {
//this function is registered in the html body tag
stage = new createjs.Stage("canvas"); //create a Stage object to work with the canvas element
img = new Image(); //create an Image object, then set its source property
img.onload = handleImageLoad //register a handler for the onLoad event
queue = new createjs.LoadQueue();
queue.addEventListener('complete', handleImageLoad);
queue.loadManifest([
id="img", img.src="my_photo.jpg"
])
}
function handleImageLoad(event) {
//this function runs when the onload event completes
map = new createjs.Bitmap(img); //create a Bitmap object, then set properties
map.x = 0;
map.y = 0;
stage.addChild(map); //add the Bitmap object as a child of the stage, then update the stage
stage.update();
}
</script>
</head>
<body onload="init();">
<!==add a canvas tag==>
<canvas id="canvas" width="640" height="480"></canvas>
</body>
</html>
I recomend you AngularJS.
You have to call a function on HTML:
<body ng-init="initCanvas()">
<center>
<canvas id="canvas" width="602" height="447"></canvas>
</center>
</body>
In JavaScript:
var stage, image;
var initCanvas = function() {
stage = new createjs.Stage("canvas");
image = new createjs.Bitmap("img/image.png");
image.x = 0; image.y = 0; image.visible = true;
stage.addChild(image);
stage.update();
};

Javascript - image displaying over text

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);
}

Image not loading from startup

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!

Categories

Resources