my images wont load at the first time click [duplicate] - javascript

This is my easel js function, it draws a red circle and an image, however the circle is showing but the image isn't.
function Start() {
var stage = new createjs.Stage("DogeCanvas");
var dog = new createjs.Bitmap("doge.jpg");
var circle = new createjs.Shape();
circle.graphics.beginFill("red").drawCircle(0, 0, 50);
circle.x = 100;
circle.y = 100;
dog.x=100;
dog.y=100;
stage.addChild(circle, dog);
stage.update();
}
And this is the html file
<!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>
Why? help please, seems like in everyones else code this works but why this isn't working for me?

The image is likely not loaded yet.
You can add a Ticker to the stage to constantly update it (which most applications do, since there is other things changing over time)
Example:
createjs.Ticker.on("tick", stage);
// OR
createjs.Ticker.addEventListener("tick", stage);
// OR
createjs.Ticker.on("tick", tick);
function tick(event) {
// Other stuff
stage.update(event);
}
Listen for the onload of the image, and update the stage again
Example:
var bmp = new createjs.Bitmap("path/to/image.jpg");
bmp.image.onload = function() {
stage.update();
}
Preload the image with something like PreloadJS before you draw it to the stage. This is a better solution for a larger app with more assets.
Example:
var queue = new createjs.LoadQueue();
queue.on("complete", function(event) {
var image = queue.getResult("image");
var bmp = new createjs.Bitmap(image);
// Do stuff with bitmap
});
queue.loadFile({src:"path/to/img.jpg", id:"image"});

Related

Functions With Easel JS

I am trying (and failing) miserably with Easel JS and Canvas. I'm a bit new to canvas in general and learning JS as well. I am basically trying to make a canvas that I can update with colors, that are passed through a button click.
I have made a Fiddle to show my work so far.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>IllustratorSetup</title>
<script src="https://code.createjs.com/easeljs-0.8.2.min.js"></script>
<script>
var stage = new createjs.Stage("canvas");
var circle = new createjs.Shape();
function drawRectangle(){
var rect = new createjs.Shape();
rect.graphics.beginFill("#000").drawRect(10, 10, 80, 80);
stage.addChild(rect);
stage.update();
}
function drawShapes(){
drawRectangle();
stage.update();
}
</script>
</head>
<body onload="drawShapes()">
<canvas id="canvas" width="500" height="300"></canvas>
<button onclick="drawRectangle('#ff0000')">Click me for red</button>
</body>
</html>
Your demo likely doesn't work because you are defining your stage before the body onload, and passing it the ID of your canvas (which uses a document.getElementById under the hood). The canvas element won't be available until it is created in the body.
I recommend moving your code that isn't in a function to an init(), or even put it into the drawShapes method.
var stage, circle; // Keep them global
function drawRectangle(){
var rect = new createjs.Shape();
rect.graphics.beginFill("#000").drawRect(10, 10, 80, 80);
stage.addChild(rect);
//stage.update(); // Unnecessary, since it is called in drawShapes.
}
function drawShapes(){
stage = new createjs.Stage("canvas");
circle = new createjs.Shape();
drawRectangle();
stage.update();
}
You can also define your scripts in the body, after the canvas element, so that they initialize after the element is ready.
Note that your fiddle doesn't have the createjs libraries in it, and that JSFiddle will fire the code part of the fiddle during the onload event, so you may not see the issue you are having locally.

Creating simple text tweening with CreateJS

I've started to learn how to use CreateJS. I'm trying to make a simple text tweening. So I have this code:
<script src="http://code.createjs.com/createjs-2013.12.12.min.js"></script>
<script>
function init() {
var c = createjs;
var stage = new c.Stage("myCanvas");
var txt = new c.Text("Hola!", "bold 16px Arial");
txt.alpha = 0.2;
stage.addChild(txt);
c.Tween.get(txt)
.to({alpha:1}, 1500)
.to({text:"Ciao!"}, 800)
.to({rotation:360, text:"Hello"}, 1300)
.to({y:380}, 2000, c.Ease.bounceOut)
.wait(1000)
.call(alert, ["Done animating!"], window);
stage.update();
}
</script>
</head>
<body onLoad="init();">
<canvas id="myCanvas" width="300" height="400">Canvas not supported</canvas>
</body>
I see my text on the canvas, it has alpha 0.2, it even pops up the alert in the end, but I don't see any motion on the canvas. What am I doing wrong?
stage.update(); needs to be called repeatedly in order to correctly render animations, the most common way is to call it on every tick.
createjs.Ticker.addEventListener("tick", function() {
stage.update();
});
Add this to your code and then it should work properly.

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

Canvas Clear in Paper.js

Does anyone know the best way to clear a canvas using paper.js
I tried the regular canvas clearing methods but they do not seem to work with paper.js
Html
<canvas id="myCanvas" style="background:url(images/graphpaper.jpg); background-repeat:no-repeat" height="400px" width="400px;"></canvas>
<button class="btn btn-default button" id="clearcanvas" onClick="clearcanvas();" type="button">Clear</button>
Javascript/Paperscript
<script type="text/paperscript" canvas="myCanvas">
// Create a Paper.js Path to draw a line into it:
tool.minDistance = 5;
var path;
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
function onMouseDown(event) {
// Create a new path and give it a stroke color:
path = new Path();
path.strokeColor = 'red';
path.strokeWidth= 3;
path.opacity="0.4";
// Add a segment to the path where
// you clicked:
path.add(event.point, event.point);
}
function onMouseDrag(event) {
// Every drag event, add a segment
// to the path at the position of the mouse:
path.add(event.point, event.point);
}
</script>
Regular clearing does not work because paper.js maintains a scene graph and takes care of drawing it for you. If you want to clear all items that you have created in a project, you need to delete the actual items:
project.activeLayer.removeChildren(); works as long as all your items are inside one layer. There is also project.clear() which removes everything, including the layer.
In case someone comes looking for an answer with little experience in Javascript, I made a simple example :
1) As Jürg Lehni mentioned project.activeLayer.removeChildren(); can be used to remove all items inside active layer.
2) To reflect the cleaning you have to call paper.view.draw();.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Circles</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="paper-full.js"></script>
<script type="text/paperscript" canvas="canvas">
function onMouseUp(event) {
var circle = new Path.Circle({
center: event.middlePoint,
radius: event.delta.length / 2
});
circle.strokeColor = 'black';
circle.fillColor = 'white';
}
</script>
<script type="text/javascript">
paper.install(window);
window.onload = function () {
paper.setup('canvas');
document.getElementById('reset').onclick = function(){
paper.project.activeLayer.removeChildren();
paper.view.draw();
}
};
</script>
</head>
<body>
<canvas style="background-color: #eeeeed" id="canvas" resize></canvas>
<input id="reset" type="button" value="Reset"/>
</body>
</html>
CSS :
html,
body {
margin: 0;
overflow: hidden;
height: 100%;
}
/* Scale canvas with resize attribute to full size */
canvas[resize] {
width: 58%;
height: 100%;
}
you can use project.activeLayer.removeChildren(); for clear entire layer,
or you can add your new paths to group and remove all childrens in group
var myPath;
var group = new Group();
function onMouseDown(event) {
myPath = new Path();
}
function onMouseDrag(event) {
myPath.add(event.point);
}
function onMouseUp(event) {
var myCircle = new Path.Circle({
center: event.point,
radius: 10
});
myCircle.strokeColor = 'black';
myCircle.fillColor = 'red';
group.addChild(myCircle);
}
// connect your undo function and button
document.getElementById('clearbutton').onclick = btnClear;
function btnClear(){
group.removeChildren();
}
c.width = c.width; ctx.clearRect(0,0,c.width,c.height); should be a good catchall if you've not tried it.
Beware however - setting canvas width will reset the canvas state including any applied transforms.
A quick google took me to https://groups.google.com/forum/#!topic/paperjs/orL7YwBdZq4 which specifies another (more paper.js specific) solution:
project.activeLayer.removeChildren();

Easel.js: Browser compatibility when placing an image within a container and adding mouse interactions

I'm going to start this question off by saying that this is 100% working in Firefox (v21.0). For some reason it's not working in Google Chrome (v27.0.1453.94m). It also doesn't work in IE10.
Here is the JavaScript code I'm having issues with:
function canvasDrawBackground(value){
console.log(value);
stage.removeChild(background);
var temp = new createjs.Bitmap("images/bg_" + value +".jpg");
background = new createjs.Container();
background.x = background.y = 0;
background.addChild(temp);
stage.addChild(background);
background.addEventListener("mousedown", function(evt) {
var offset = {x:evt.target.x-evt.stageX, y:evt.target.y-evt.stageY};
evt.addEventListener("mousemove",function(ev) {
ev.target.x = ev.stageX+offset.x;
ev.target.y = ev.stageY+offset.y;
stage.update();
});
});
stage.update();
}
So, in Firefox the above code works, as in the image is added to the canvas and you can drag it around.
In Chrome / IE10 nothing happens - or more simply nothing appears on the canvas. I think the issue is in regards to when I add the image into the container, as I can place other items into the container and it works.
I am using http://code.createjs.com/easeljs-0.6.1.min.js and this code is based off of the "drag" tutorial. Here's the code from the tutorial:
<!DOCTYPE html>
<html>
<head>
<title>EaselJS demo: Dragging</title>
<link href="../../shared/demo.css" rel="stylesheet" type="text/css">
<script src="http://code.createjs.com/easeljs-0.6.0.min.js"></script>
<script>
var stage, output;
function init() {
stage = new createjs.Stage("demoCanvas");
// this lets our drag continue to track the mouse even when it leaves the canvas:
// play with commenting this out to see the difference.
stage.mouseMoveOutside = true;
var circle = new createjs.Shape();
circle.graphics.beginFill("red").drawCircle(0, 0, 50);
var label = new createjs.Text("drag me", "bold 14px Arial", "#FFFFFF");
label.textAlign = "center";
label.y = -7;
var dragger = new createjs.Container();
dragger.x = dragger.y = 100;
dragger.addChild(circle, label);
stage.addChild(dragger);
dragger.addEventListener("mousedown", function(evt) {
var offset = {x:evt.target.x-evt.stageX, y:evt.target.y-evt.stageY};
// add a handler to the event object's onMouseMove callback
// this will be active until the user releases the mouse button:
evt.addEventListener("mousemove",function(ev) {
ev.target.x = ev.stageX+offset.x;
ev.target.y = ev.stageY+offset.y;
stage.update();
});
});
stage.update();
}
</script>
</head>
<body onLoad="init();">
<canvas id="demoCanvas" width="500" height="200">
alternate content
</canvas>
</body>
</html>
To simulate my issue, change "var circle = new createjs.Shape();" into a bitmap / image, createjs.Bitmap("images/bg_" + value +".jpg");. It then doesn't render.
Any help is greatly appreciated! Hopefully I'm just doing it wrong. :P
This is probably because the image is not loaded. If you only update the stage after creating it, the image may not display. I would recommend adding a callback to the image to update the stage after its loaded.
// Simple approach. May not work depending on the scope of the stage.
var temp = new createjs.Bitmap("images/bg_" + value +".jpg");
temp.image.onload = function() { stage.update(); }
It also may make sense to preload the images you intend to use.

Categories

Resources