Adding a simple image in easeljs - javascript

This is my htmlcode:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="http://code.createjs.com/easeljs-0.7.0.min.js"></script>
<script src="Doge.js"></script>
</head>
<body bgcolor="#C7C7C7" onload="Start();">
<canvas id="DogeCanvas" width="480" height="320"></canvas>
</body>
</html>
And this is my Doge.js code:
function Start() {
var stage = new createjs.Stage("DogeCanvas");
var doge = new Image();
doge.src = "images/doge.jpg"
var bitmap = new createjs.Bitmap(doge);
stage.addChild(bitmap);
stage.update();
}
Why it doesn't show anything on the screen?
What is wrong?

The image is not loaded when the stage is updated. I posted an answer here:
ยป easeljs not showing bitmap
You can add a Ticker to the stage to constantly update it (which most applications do, since there is other things changing over time)
Listen for the onload of the image, and update the stage again
Preload the image with something like PreloadJS before you draw it to the stage.

As stated above you cannot draw your image until you have loaded it. Try this:
<!DOCTYPE HTML>
<html>
<title>Easel Test</title>
<head>
<script src="https://code.createjs.com/easeljs-0.8.0.min.js"></script>
<script>
var stage;
function init() {
stage = new createjs.Stage("myCanvas");
var image = new Image();
image.src = "path/image";
image.onload = handleImageLoad;
}
function handleImageLoad(event) {
var image = event.target;
var bitmap = new createjs.Bitmap(image);
stage.addChild(bitmap);
stage.update();
}
</script>
</head>
<body onload="init();">
<canvas id="myCanvas" width="960" height="580"></canvas>
</body>
</html>

Related

canvas is not merging and resulting in showing only background image

I have create 2 canvas, load two differnt image and I want to merge both canvas and then display it as image in <div id="test"></div> tag.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>canvas to image</title>
</head>
<body>
<div>
<canvas id="card_canvas" width="800" height="500"></canvas>
<canvas id="card_canvas2" width="800" height="500"></canvas>
</div>
<div id="test"></div>
<button onclick="canvasToImage()">canvas to image</button>
<script>
var img1 = new Image();
img1.src = "images/img1.jpg";
var cuimg;
function canvasToImage(){
var canvass1 = document.getElementById("card_canvas");
var canvass2 = document.getElementById("card_canvas2");
var ctx1 = canvass1.getContext('2d');
var ctx2 = canvass2.getContext('2d');
ctx1.drawImage(img1, 0, 0);
cuimg = new Image();
cuimg.onload = function(){
ctx2.drawImage(cuimg, 7, 92);
}
cuimg.src = "images/img2.jpg";
ctx1.drawImage(canvass2, 0, 0);
var imgdata = canvass1.toDataURL('image/png');
var mergeimg = document.createElement("img");
mergeimg.src = imgdata;
document.getElementById("test").appendChild(mergeimg);
}
</script>
</body>
</html>
Here is img1.jpg:
Here is img2.jpg:
This code ends up in displaying only background image:
I am expecting:
This can be achieve by simply setting following style on canvas2:
<canvas id="card_canvas2" style="position:absolute; left:0px; top:0px;"></canvas>
https://jsfiddle.net/jkjqd7gz/
I've been fiddling with your code a bit, and I think I've figured out the issue. javascript has a funny execution order at times that most people aren't aware of. Your onload lambda function is causing some of the issues your experiencing. Basically, you need to move your ctx1.drawImage(canvass2, 0, 0); line inside your lambda function just after ctx2.drawImage(cuimg, 7, 92); To understand what I mean open your code and hit the canvas to image button twice. The first time populates both canvasses, the second time puts the contents of canvass2 onto canvass1. I could probably explain exactly what's happening in terms of order of execution, but the explanation involves some difficult to understand concepts regarding parallelism, swap buffers, and race conditions.
To put it in a nutshell, whatever function you call ctx2.drawImage in, you need to then follow it with ctx1.drawImage. Honestly though, the best way to make composite images is to create a sprite class that stores an image, its postion, and layer information if desired. Then use a dynamic array to store the sprites. Always clear the canvas every time before you draw on it and loop through the contents of your arrays drawing each sprite in layer order on its respective canvass. Finally, I would use one set of functions to populate the canvas and a second to merge them.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>canvas to image</title>
</head>
<body>
<div>
<canvas id="card_canvas" width="800" height="500"></canvas>
<canvas id="card_canvas2" width="800" height="500"></canvas>
</div>
<div id="test"></div>
<button onclick="popCanvas()">Populate Canvasses</button>
<button onclick="canvasToImage()">Canvas Combine</button>
<script>
var img1 = new Image();
img1.src = "images/img1.jpg";
var cuimg = new Image();
var canvass1 = document.getElementById("card_canvas");
var canvass2 = document.getElementById("card_canvas2");
function popCanvas(){
var ctx1 = canvass1.getContext('2d');
var ctx2 = canvass2.getContext('2d');
ctx1.clear()
ctx2.clear()
ctx1.drawImage(img1, 0, 0);
cuimg.onload = function(){
ctx2.drawImage(cuimg, 7, 92);
}
cuimg.src = "images/img2.jpg";
}
function canvasToImage(){
var ctx1 = canvass1.getContext('2d');
var ctx2 = canvass2.getContext('2d');
ctx1.drawImage(canvass2, 0, 0);
var imgdata = canvass1.toDataURL('image/png');
var mergeimg = document.createElement("img");
mergeimg.src = imgdata;
document.getElementById("test").appendChild(mergeimg);
}
</script>
</body>
</html>

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>

I have trouble connecting js files using html

What I want do find out is how I can make this work so it makes a red box at location 100,100, using a function as my main function and another function to draw the image but I want it to be in a different js file.
2 js files and 1 html file.
Code
//HTML code
<!DOCTYPE html>
<html lang ="en">
<head>
<meta charset="UTF-8">
<title>Prufa Einar</title>
</head>
<body>
<canvas id = "myCanvas" width="600" height = "600"
style ="border: 1px solid black;">
<script type = "text/javascript" src "draw.js"></script>
<script type = "text/javascript" src "main.js"></script>
<script type = "text/javascript">
main();
</script>
</body>
</html>
//first js.file
var canvas;
var ctx;
var main = function()
{
canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
draw(ctx);
};
//second js file
var draw = function(ctx)
{
{
ctx.fillStyle = "Red";
ctx.fillRect(100,100,20,20);
}
};
Looks like you need equal sign after src.
src=""
and canvas out of head into body instead

Canvas images do not load until click event... I want to load when page loads, how?

I am creating Battleships, the board game on an HTML5 canvas. I have a problem loading my ship images when the page is loaded. For some reason, the ship images only show when I click somewhere on the screen.
background info:
1.I have 2 canvas elements, each with 2 contexts
2.If I put the PlayerGrid.js before the OpponentGrid.js I have to click on the screen to get my ships to show up.
3.The Draw() is what draws the grid, and the images once they are created from the createShips(). createships() simply creates different ship objects and assigns images to each object.
4.I DO TRY CALLING DRAW() in many places, the onload, and the createShips(), but they still do not show.
Does anybody know what it could be? Is it a conflict in the context or canvases? The ship images DO show when I put the OpponentGrid.js BEFORE my PlayerGrid.js, but then there is a huge problem with my XMLHttpRequest that isn't worth solving.
How else should I call my Draw method after everything is loaded? Should I call my Draw() in my Battleship.html at the end somewhere?
Here's how to be sure all your images are loaded before you use them
Code and a Fiddle: http://jsfiddle.net/m1erickson/nD5jr/
<!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 canvas1=document.getElementById("canvas1");
var ctx1=canvas1.getContext("2d");
var canvas2=document.getElementById("canvas2");
var ctx2=canvas2.getContext("2d");
var imageURLs=[];
var imagesOK=0;
var imagesFailed=0;
var imgs=[];
imageURLs.push("http://upload.wikimedia.org/wikipedia/commons/d/d4/New_York_City_at_night_HDR_edit1.jpg");
imageURLs.push("http://www.freebestwallpapers.info/bulkupload//20082010//Places/future-city.jpg");
loadAllImages();
function loadAllImages(){
for (var i = 0; i < imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = onLoad;
img.onerror = onFail;
img.src = imageURLs[i];
}
}
var imagesAllLoaded = function() {
if (imagesOK+imagesFailed==imageURLs.length ) {
// ALL IMAGES ARE NOW PROCESSED
// ready to use loaded images
// ready to handle failed image loads
ctx1.drawImage(imgs[0],0,0,canvas1.width,canvas1.height);
ctx2.drawImage(imgs[1],0,0,canvas2.width,canvas2.height);
}
};
function onLoad() {
imagesOK++;
imagesAllLoaded();
}
function onFail() {
// possibly log which images failed to load
imagesFailed++;
imagesAllLoaded();
};
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas1" width=300 height=300></canvas><br/>
<canvas id="canvas2" width=300 height=300></canvas>
</body>
</html>

Canvas toDataURL doesn't return whole URL on first try

I've got some code which takes a drawing made on in SVG with Raphael (a 400x400 image loaded into the SVG with Raphael), converts it to a canvas with canvg, and should then take canvas.toDataURL and make it an image. All of this should happen when a button is pushed. The first two steps work, but the third is glitchy. The first time I press the button, a 300x150 blank image is placed in the final div instead of the 400x400 image. If I press the button again, the image shows up fine (correct size and everything). I've tried to use both img.onload and the jquery version $(img).load but neither seems to keep the problem from happening. Therefore, I feel like it's an issue with the canvas having not been drawn completely yet but I can't prove that and I can't seem to make the code wait until it has been drawn. Below is all the code. I tried to make it a fiddle but I kept getting security errors with the image.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/raphael.js"></script>
<script type="text/javascript" src="scripts/excanvas.compiled.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var nowX, nowY, R = Raphael("svg_drawing", 400, 400);
$($("svg").get(0)).attr("xmlns:xlink", "http://www.w3.org/1999/xlink");
var templ = R.image("images/band_clutch.jpg", 0, 0, 400, 400);
});
function toImg(){
var svg = $("#svg_drawing").html().replace(/>\s+/g, ">").replace(/\s+</g, "<");
var canvas = $("#canvas")[0];
canvg(canvas, svg);
var imgData = canvas.toDataURL('image/jpg');
var img = new Image();
$(img).load(function(){
$("#drawing_area").html("");
$(img).appendTo("#drawing_area");
});
img.src = imgData;
}
</script>
<title>Sandbox</title>
</head>
<body style="margin: 0; width:3000px">
<div id="svg_drawing" style="background-color:white;display:inline-block;height:400px;width:400px;border:1px solid black;"></div>
<canvas id="canvas" style="display:inline-block;height:400px;width:400px;border:1px solid red;"></canvas>
<div id="drawing_area" style="background-color:white;display:inline-block;height:400px;width:400px;border:1px solid black;"></div>
<button onclick="toImg()" style="display:inline-block;vertical-align:top;">Do it</button>
</body>
</html>
It sounds like the canvas area is staying at the default 350 x 150. Try setting
canvas.width = canvas.height = 400;
before drawing (keep the inline CSS as-is).
To fix the actual rendering issue, you need to tell the canvg method to do the toDataURI stuff asyncronously, once the rendering has been complete:
function toImg(){
var svg = $("#svg_drawing").html().replace(/>\s+/g, ">").replace(/\s+</g, "<");
var canvas = $("#canvas")[0];
canvg(canvas, svg, {
renderCallback : function(){
var imgData = canvas.toDataURL('image/jpg');
var img = new Image();
$(img).load(function(){
$("#drawing_area").html("");
$(img).appendTo("#drawing_area");
});
img.src = imgData;
}
});
}

Categories

Resources