Animating Color with Tweenjs - javascript

I've recently switched to EaselJs and would like to animate the color of a circle.
The code I've got so far is this:
var shape = new createjs.Shape();
shape.graphics.beginFill(createjs.Graphics.getRGB(255, 0, 0));
shape.graphics.drawCircle(0, 0, 10);
stage.addChild(shape);
var tween = createjs.Tween.get(shape, { loop: true }).
to({color:"#00FF00" }, 1000);
but that doesn't work. What is the right property to animate?

I don't think it's possible to animate the color of a shape like that, afterall the drawing of your shape could include many different colors, how should the Tween know which of those colors to modify?
There are two ways that I can think of right know:
Method 1) Use a createjs.ColorFilter, apply it to your shape and then tween the properties of your filter:
var shape = new createjs.Shape();
//making the shape shape white, so we can work with the multiplyers of the filter
shape.graphics.beginFill(createjs.Graphics.getRGB(255, 255, 255));
shape.graphics.drawCircle(0, 0, 10);
stage.addChild(shape);
var filter = new createjs.ColorFilter(1,0,0,1); //green&blue = 0, only red and alpha stay
shape.filters = [filter];
var tween = createjs.Tween.get(filter, { loop: true }).
to({redMultiplier:0, greenMultiplier:1 }, 1000);
I did not test this, so...let me know it this works. Also note, that filters are only applied/updated when calling cache() or updateCache() on your shape, so you will have to add that to your tick-function.
Method 2) Or you just redraw the shape every frame...but 1) is probably easier.

I was just trying to do the same thing. My solution was to tween custom properties on the shape object and then call an update method on the tween 'change' event. hope it this helps, I'm really new to createjs but so far I really like it!
var s = new createjs.Shape();
s.redOffset = 157;
s.blueOffset = 217;
s.greenOffset = 229;
s.updateColor = function()
{
var color = createjs.Graphics.getRGB(
parseInt(this.redOffset),
parseInt(this.greenOffset),
parseInt(this.blueOffset),
1);
this.graphics.beginFill( color ).drawRect(0, 0, 300, 300);
}
createjs.Tween.get(this.background).to({
redOffset : 255,
greenOffset : 255,
blueOffset : 255
}, 3000).addEventListener('change', function()
{
s.updateColor ();
});

Non filter version.
var colorObj = { r:255, g:0, b:0 };
var shape = new createjs.Shape();
var command = shape.graphics.beginFill(createjs.Graphics.getRGB(colorObj.r, colorObj.g, colorObj.b)).command;
shape.graphics.drawCircle(60, 60, 10);
stage.addChild(shape);
var tween = createjs.Tween.get(colorObj, { loop: true }).to({ r:255, g:255, b:255 }, 1000);
tween.addEventListener( "change", function( event ) {
command.style = createjs.Graphics.getRGB(Math.floor(colorObj.r), Math.floor(colorObj.g), Math.floor(colorObj.b));
});
beginFill(...).command object is able to update.
fiddle
https://jsfiddle.net/MasatoMakino/uzLu19xw/

I just read another option for animating colors here: http://community.createjs.com/discussions/easeljs/4637-graphics-colour-animation
It makes use of the createjs inject-method. I copied the relevant code from the provided code-example with a little bit of explanation fo my own.
According to the docs:
inject ( callback, data ):
Provides a method for injecting arbitrary Context2D (aka Canvas) API calls into a Graphics queue. The specified callback function will be called in sequence with other drawing instructions (...)
With this method you can for example change the native context2d fillstyle so we can change the fill color that easeljs uses to draw on the canvas.
Here we tell createjs about our own setColor function (defined below), this function will thus get automatically executed before every redraw:
var shape = new createjs.Shape();
shape.graphics.beginFill(createjs.Graphics.getRGB(255, 0, 0));
shape.graphics.inject(setColor, data)
shape.graphics.drawCircle(0, 0, 10);
stage.addChild(shape);
The definition of the setColor-function which calls the canvas native fillStyle method:
function setColor(o) {
// sets the context2D's fillStyle to the current value of data.fill:
this.fillStyle = o.fill; // "this" will resolve to the canvas's Context2D.
}
And the tick-function which changes the value of the fill:
function tick(evt) {
count = (count+3)%360;
// update the value of the data object:
data.fill = createjs.Graphics.getHSL(count, 100, 50);
// redraw the stage:
stage.update();
}

Modifying fill Instructions will do the trick of changing the color. This might help in doing the animation.
I dont know the impacts of this, but this works very fine for me.
Try this,
var circle = new createjs.Shape();
circle.graphics.f('#ffffff').s('#000000').ss(0.7).arc((30 * j),50,10, 0, Math.PI * 2, 1);
circle.number = j;
circle.addEventListener('click', function(e) {
var fillStyle = e.target.graphics._fillInstructions[0].params;
var currentFillStyle=fillStyle[1]+"";
for (var i = 0; i < circles.length; i++) {
var resetFillStyle = circles[i].graphics._fillInstructions[0].params;
resetFillStyle[1] = "#ffffff";
}
if (currentFillStyle == "#00B4EA") {
fillStyle[1] = "#FFFFFF";
} else {
fillStyle[1] = "#00B4EA";
}
stage.update();
})
Hope this helps!

Related

How to see if PNG has a transparent background with Javascript [duplicate]

Is there a way to read transparent pixels from a picture using javascript?
I think, that it could be something similar to what PNG fixes does for IE (reading transparent pixels and applying some stuff, lol). But yes, for every browser..
Ah, would be awesome if it could be achieved without HTML5.
Well this question is actually answered by the dude from GoogleTechTalks in this video on javascript-based game engines.
http://www.youtube.com/watch?feature=player_detailpage&v=_RRnyChxijA#t=1610s
It should start at the point where it is explained.
Edit:
So I will summarize what is told in the video and provide a code-example.
It was a lot tougher than I had expected. The trick is to load your image onto a canvas and then check each pixel if it is transparent. The data is put into a two dimension array. Like alphaData[pixelRow][pixelCol]. A 0 is representing transparency while a 1 is not. When the alphaData array is completed it is put in global var a.
var a;
function alphaDataPNG(url, width, height) {
var start = false;
var context = null;
var c = document.createElement("canvas");
if(c.getContext) {
context = c.getContext("2d");
if(context.getImageData) {
start = true;
}
}
if(start) {
var alphaData = [];
var loadImage = new Image();
loadImage.style.position = "absolute";
loadImage.style.left = "-10000px";
document.body.appendChild(loadImage);
loadImage.onload = function() {
c.width = width;
c.height = height;
c.style.width = width + "px";
c.style.height = height + "px";
context.drawImage(this, 0, 0, width, height);
try {
try {
var imgDat = context.getImageData(0, 0, width, height);
} catch (e) {
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
var imgDat = context.getImageData(0, 0, width, height);
}
} catch (e) {
throw new Error("unable to access image data: " + e);
}
var imgData = imgDat.data;
for(var i = 0, n = imgData.length; i < n; i += 4) {
var row = Math.floor((i / 4) / width);
var col = (i/4) - (row * width);
if(!alphaData[row]) alphaData[row] = [];
alphaData[row][col] = imgData[i+3] == 0 ? 0 : 1;
}
a=alphaData;
};
loadImage.src = url;
} else {
return false;
}
}
I got errors when running local in Firefox and the try catch statement solved it. Oh I gotta eat...
Edit 2:
So I finished my dinner, I'd like to add some sources I used and wich can be helpful.
https://developer.mozilla.org/En/HTML/Canvas/Pixel_manipulation_with_canvas
Info about the imageData object.
http://blog.nihilogic.dk/2008/05/compression-using-canvas-and-png.html
Even more info about the imageData object and it's use.
http://www.nihilogic.dk/labs/canvascompress/pngdata.js
A really helpful example of the use of imageData, the code I provided resembles this one for a big part.
http://www.youtube.com/watch?v=_RRnyChxijA
Infos on scripting game-engines in javascript, really really interesting.
http://blog.project-sierra.de/archives/1577
Infos about the use of enablePrivilege in firefox.
This is a bit tricky problem, since the only way to access files directly from Javascript is by using FileReader, which is a relatively new feature and not yet supported in most browsers.
However, you could get the desired result by using a canvas. If you have a canvas, you could assign it some distinctive color (such as neon green used in green screens). Then you could insert the image onto canvas and use the method mentioned here to get each individual pixel. Then you could check each pixel's color and see whether that point corresponds to your background color (ergo it's transparent) or does it have some other color (not transparent).
Kind of hackish, but don't think there's anything else you can do with pure JS.
It appears that GameJS can do this and much, much more. I am referencing this SO question for any/all of my knowledge, as I don't claim to actually have any about this topic.
Of course, this is HTML5, and uses the canvas element.

event data in pixi.js

I just started playing around with pixi and have drawn multiple rectangles from an array with pixel coordinates like this:
var rectangle = [....];
....
var stage = new PIXI.Stage();
var renderer = PIXI.autoDetectRenderer(wrapper.getWidth(), wrapper.getHeight(), { transparent: true });
....
var graphics = new PIXI.Graphics();
graphics.interactive = true;
graphics.on("mouseover", function(e) {
this.alpha = 0.5;
}).on("mouseout", function() {
this.alpha = 1;
});
graphics.beginFill(0xFFFFFF);
graphics.lineStyle(2, 0x000000);
for (var i = 0; i < rectangle.length; i++) {
graphics.drawRect(rectangle[i][0], rectangle[i][1], 10, 10);
}
graphics.endFill();
stage.addChild(graphics);
renderer.render(stage);
The events are triggered but the object I get by "e" or "this" inside the callback is the object for all graphics. I want to get that single "mouseovered" rectangles object I can see in the graphicsData, but there is no id or anything to identify it by. How can I do this?
Performance is of essence as I'm going to render 20k+ rectangles or circles.
Without drawing each rectangle onto it's own PIXI.Graphics object you won't be able to get individual mouseover events. This is because as far as PIXI is concerned the Graphics object is a single bitmap image.
I would suggest performing your own hit tests inside the mouseover function to detect which rectangle the cursor is over.
If you are using PIXI.Rectangles you can take advantage of the built in Rectangle.Contains function to check if a point (in this case the mouse position) is inside the bounds.

Collision Detection with Javascript, Canvas, and Alpha Detection

I'm currently working on a basic javascript game that has two sprites that are not to be collided together. However, basic bounding box collision won't suffice as there are portions of the sprites that are transparent and wouldn't 'count' as colliding. I found a solution to the problem that I am having, but I can't get it to work. What I would like to do is calculate the transparent portions of the sprites and make sure that if the transparent portions overlap, that there is no collision detected. Here is what I found that solves the problem.
http://blog.weeblog.net/?p=40#comments
/**
* Requires the size of the collision rectangle [width, height]
* and the position within the respective source images [srcx, srcy]
*
* Returns true if two overlapping pixels have non-zero alpha channel
* values (i.e. there are two vissible overlapping pixels)
*/
function pixelCheck(spriteA, spriteB, srcxA, srcyA, srcxB, srcyB, width, height){
var dataA = spriteA.getImageData();
var dataB = spriteB.getImageData();
for(var x=0; x<width; x++){
for(var y=0; y<height; y++){
if( (dataA[srcxA+x][srcyA+y] > 0) && (dataB[srcxB+x][srcyB+y] > 0) ){
return true;
}
}
}
return false;
}
And for calculating the image data:
/**
* creating a temporary canvas to retrieve the alpha channel pixel
* information of the provided image
*/
function createImageData(image){
$('binaryCanvas').appendTo('body');
var canvas = document.getElementById('binaryCanvas');
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
var canvasData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var imageData = [image.width];
for(var x=0; x<image.width; x++){
imageData[x] = [image.height];
for(var y=0; y<image.height; y++){
var idx = (x + y * image.width) * 4;
imageData[x][y] = canvasData.data[idx+3];
}
}
$("#binaryCanvas").remove();
return imageData;
}
The problem is that I don't know how to implement this solution, or if this is the best solution to my problem. Is this what I'm looking for? And if so, where do I put these methods? The thing that I'm most confused about is what I should be passing to spriteA and spriteB. I've tried passing Images and I've tried passing the imageData returned from the pixelCheck method, but receiving the same error: that the object or image has no method 'getImageData'. What am I doing wrong?
Two things are wrong with this.
You made a function:
function createImageData(image){...}
But what you are calling is:
spriteA.getImageData();
spriteB.getImageData();
The dot notates a property of an object. You were trying to call a function that was never part to the objects. There are some simple fixes.
add the createImageData() function to your constructor :
function Sprite(){
...
this.createImageData = function(image){...};
...
}
or :
Sprite.createImageData = function(image{...};
or just call it correctly:
createImageData(spriteA.image); // or whatever the image is
Second, your function calls for an image parameter, but you aren't supplying one. Simply remember to supply the image when you call it. You could also remove the parameter and get the image from within the function.
Sort of like this:
function Sprite(){
...
this.createImageData = function(){
var image = this.image;
// or just use this.image, or whatever it is
...
}
...
}
Hope this helped.

KineticJs group.setSize(300,300) not working

I am trying to change size of kinetic group. but it gives JavaScript error message.
in kinetic js document its written than setSize works with group nodes
I think the documents are a bit outdated in that respect. Groups do not have a drawFunc so they do not have a width or height. If they ever do get width and height, it will be possible to create clipped groups, which will be nice. However, as they are now, groups are simply used to define a relative x and y starting coordinate for objects contained within them. This makes moving several objects at once possible (dragging, moveTo, event handlers, etc...), but that's about it.
JsFiddle as requested
var group = new Kinetic.Group({
x: 220,
y: 40,
draggable: true
});
Just make your group draggable and add your objects to the group.
The code below will allow you to create a group with clipping properties.
Instantiate it like a group, where width and height is your clipping box.
Kinetic.Clipper = function(config) {
this._initGroup(config);
};
Kinetic.Clipper.prototype = {
_initGroup: function(config) {
this.nodeType = 'Group';
Kinetic.Container.call(this, config);
},
drawScene: function() {
if(this.isVisible()) {
var context = this.getLayer().getContext();
var width = this.getWidth(), height = this.getHeight();
context.save();
context.beginPath();
context.rect(0, 0, width, height);
context.clip();
var children = this.children, len = children.length;
for(var n = 0; n < len; n++) {
children[n].drawScene();
}
context.restore();
}
},
};
Kinetic.Global.extend(Kinetic.Clipper, Kinetic.Container);
Document is outdated or wrong.
It is not possible to directly change group size

Image appearing multiple times on canvas?

I'm drawing a simple dynamic canvas and I'm wondering how I can make the .png file in my drawImage method appear like 40 times at different places on my canvas at the same time?
Thanks beforehand! :)
Thank you all very much for your reply! This is as far as I've gotten now:
<script type="text/javascript">
var ctx;
var imgBg;
var imgDrops;
var x = 40;
var y = 0;
function setup() {
var canvas = document.getElementById('canvasRegn');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
setInterval('draw();', 36);
imgBg = new Image();
imgBg.src = 'dimma.jpg';
imgDrops = new Image();
imgDrops.src = 'drop.png';
}
}
function draw() {
drawBackground();
for(var i=0; i <= 40; i++) {
ctx.drawImage (imgDrops, x, y);
y += 3;
if(y > 450)
y = -20;
x=Math.random()*600;
}
}
function drawBackground(){
ctx.drawImage(imgBg, 0, 0);
}
</script>
My problem is now that the images are jumping all over the place... I want them "falling" down slowly from above and coming back around:(
Have a look at this fiddle http://jsfiddle.net/joevallender/D83uC/10/
I made it to explain some basics of canvas to a friend recently. Although I'm using shapes instead of .png files I think the loop you are looking for is the same.
The key bit of code being this loop below
setInterval(function(){
// clear stage
context.clearRect(0, 0, width, height);
for(var i = 0; i < balls.length; i++) {
balls[i].move(balls);
}
}, 1000/FPS)
FPS is a variable, and .move() is a function that calculated new co-ordinates for and then re-draws the ball object.
I think it might simply not clearing the 'stage' context.clearRect(0, 0, width, height);
EDIT Perhaps that example had too much going on in it to be useful.
Please see a much earlier version http://jsfiddle.net/joevallender/D83uC/2 that simple animates the ball. The main point remains though, you need to clear the canvas if you don't want the 'trails'
Think of canvas like windows paint, not flash. The things you have drawn aren't editable objects. You need to redraw the whole thing each time. (Unless you use a JS library that makes things seem more like flash - but I'm guessing you want to learn without helper libraries at first)
As I said, I was explaining canvas to someone recently and you can see the various stages between the two links I've sent you by changing the number on the end of the URL http://jsfiddle.net/joevallender/D83uC/3
http://jsfiddle.net/joevallender/D83uC/4
etc.
EDIT2
Or if I've misunderstood, post a jsfiddle and let us know what is wrong with it
This is what you need: http://edumax.org.ro/extra/new/imagetut/
You can get the code here: http://edumax.org.ro/extra/new/imagetut/script.js
The relevant part is this:
function draw_image(){
//draw one image code
}
window.onload = function () {
for (var i=0;i<10;i++){
for (var j=0;j<10;j++){
draw_image(10+i*40, 10+j*40, 40, 40);
}
}
}
This code only explains the concept, it will not work by itself, for a full version check the link above.

Categories