I made a simple "animation" with PhysicsJS, where I have this body:
balon = Physics.body('circle', {
x: 50,
y: random(20, 350),
vx: 0.45,
angle: random(0,360),
angularVelocity:-0.005,
radius: 60,
mass: 1,
fixed: true
});
balon.view = new Image();
balon.view.src = 'ballon.png';
All works good but I need to add a shadow for the "ball", this means that I need to use two images the "ballon.png" and the second image (the shadow) need to be fixed over the first image (don't rotate with the body).
Any idea hot to do this ?
Thank you in advance !
If you need one of the images to have a different behavior, you'll need to handle the rendering yourself.
You can add another rendering layer for shadows. If you store the shadow image inside body.shadow, then you can do something like this.
var shd = renderer.addLayer('shadows');
var bodies = [balon];
// draw the provided shadow view
shd.drawShadow = function( body, view ){
var pos = body.state.pos
,v = body.state.vel
,t = renderer._interpolateTime || 0
,x
,y
,aabb
,ctx = shd.ctx;
;
// interpolate positions
x = pos.x + v.x * t;
y = pos.y + + v.y * t;
ctx.save();
ctx.translate( x, y );
ctx.drawImage(view, -view.width/2, -view.height/2, view.width, view.height);
ctx.restore();
}
shd.render = function(){
var body;
for (var i = 0, l = bodies.length; i < l; i++){
body = bodies[ i ];
if ( body.shadow ){
shd.drawShadow( body, body.shadow );
}
}
};
Related
I have five rectangles placed at different points along a circle like this - http://imgur.com/uVYkwl7.
Upon clicking any rectangle i want the circle to move to the left of the screen, gradually scaling down it's radius until the circle's center reaches x=0. I'd like the five rectangles to move along with the circle while its being scaled down and also adjust their own positions and scale on the circle so that they are within the view's bounds, like this - http://imgur.com/acDG0Aw
I'd appreciate any help on how to go about doing this. Heres my code for getting to the 1st image and animating the circle:
var radius = 300;
var center = view.center;
var circle = new Path.Circle({
center: view.center,
radius: radius,
strokeColor: 'black',
name: 'circle'
});
var path = new Path.Rectangle({
size: [230, 100],
fillColor: '#1565C0'
});
var rectText = ['Text 1',
'Text 2',
'Text 3',
'Text 4',
'Text 5'
];
var symbol = new Symbol(path);
var corners = [
new Point(center.x, center.y - radius),
new Point(center.x - radius, center.y - radius / 2),
new Point(center.x + radius, center.y - radius / 2),
new Point(center.x - radius, center.y + radius / 2),
new Point(center.x + radius, center.y + radius / 2)
];
var rectClicked = false;
var clickedRect = null;
var rectClick = function(event) {
rectClicked = true;
clickedRect = this;
};
function onFrame(event) {
// Your animation code goes in here
if (rectClicked) {
for (var i = 0; i < 1; i++) {
var item = project.activeLayer.children[i];
if (item.name == 'circle') {
if (item.position.x < 0) {
rectClicked = false;
} else {
item.position.x -= 10;
item.scale(1/1.01);
}
}
}
}
}
// Place the instances of the symbol:
for (var i = 0; i < corners.length; i++) {
var placedSymbol = symbol.place(corners[i]);
placedSymbol.onMouseDown = rectClick;
var rText = new PointText({
point: placedSymbol.bounds.topLeft + 20,
content: rectText[i],
fontSize: '20',
fillColor: 'white'
});
}
Paper.js provides rotations around a pivot out of the box.
var pivotPoint = new Point(10, 5);
circle.rotate(30,pivotPoint);
Here is the docs reference for this behaviour and here is a very basic Sketch example to illustrate this
The above snippet will rotate a circle(you can change this to rectangle in your case) by 30 degrees around a pivot point at coordinates 10,5 on the x/y axis.
Thus what you describe is certainly doable as long as the path that your elements will follow is always circular.
Bear in mind that in order for the pivot rotation to work the way you want them to you need to update the pivotPoint and reinitiate the rotation again.
Note: In case you want to move along an arbitrary shape instead of circular path, you should search for Paper.js animation-along-a-path which is something that I've seen been done before without much difficulty - e.g this simple Sketch by the creator of Paper.js himself.
The sketch I provided above is a basic example of rotation around a pivot point.
I'm dumping the Sketch code here in case the link goes dead:
//Create a center point
var centerCircle = new Path.Circle(paper.view.center, 100);
centerCircle.strokeColor = 'black';
centerCircle.dashArray = [10, 12];
//Create the circles
var circle1Radius = 30;
var circle1 = new Path.Circle((centerCircle.position-centerCircle.bounds.width/2)+circle1Radius, circle1Radius);
circle1.fillColor = '#2196F3';
var circle2Radius = 40;
var circle2 = new Path.Circle((centerCircle.position-centerCircle.bounds.width/2)+circle2Radius, circle2Radius);
circle2.fillColor = '#E91E63';
var circle3Radius = 40;
var circle3 = new Path.Circle((centerCircle.position-centerCircle.bounds.width/2)+circle2Radius, circle2Radius);
circle3.fillColor = '#009688';
var i=0;
var animationGap = 125; //how long to move before animating the next circle
var rotationSpeed = 2;
function onFrame(event) {
circle1.rotate(rotationSpeed,centerCircle.position);
if(i>animationGap)
circle2.rotate(rotationSpeed,centerCircle.position);
if(i>animationGap*2)
circle3.rotate(rotationSpeed,centerCircle.position);
i++;
}
Purpose
I'm making a simple "shoot the word" game, where user needs to click on some moving rectangles with words to "shoot" them.
Problem
So i create some objects and move them using simple kinetic.js tweening.
Word creation
function createWord(value){
//here comes some word object construction
var wordGroup = new Kinetic.Group({
x: 0,
y: 0
});
var padding = 10;
wordGroup.label = new Kinetic.Text({
x: padding,
y: padding,
text: value,
fontFamily: 'Times New Roman',
fontSize: 30,
fill: 'white'
});
wordGroup.tag = new Kinetic.Rect({
x: 0,
y: 0,
width: wordGroup.label.width() + (padding << 1),
height: wordGroup.label.height() + (padding << 1),
fill: 'black',
shadowColor: 'black',
shadowBlur: 10,
shadowOffset: {x:10,y:20},
shadowOpacity: 0.5,
cornerRadius: 10
});
wordGroup.add(wordGroup.tag);
wordGroup.add(wordGroup.label);
wordGroup.shoot = function(){ //shooting mechanism (simple stop from moving and remove from scene)
wordGroup.tween.pause();
wordGroup.clean();
dropNextWord(); //drops fresh blood! (new word instead of shooted)
}
wordGroup.clean = function(){ //remove from scene and set it free to drop again
wordGroup.remove();
wordGroup.isActive = false;
}
wordGroup.move = function(callback){ //animates word
wordLayer.add(wordGroup);
moveToSide(wordGroup, callback); //calls moving function
}
wordGroup.on('click', function(e){
wordGroup.shoot();
});
return wordGroup;
}
Tweening part
//move word to opposite side
function moveToSide(word, callback){
var side = Math.random();
var d = 100;
spawnFromSide(word, side); //set random side word position
tweenPosition = {
x: word.x(),
y: word.y()
}
if(side < 0.25){ //left
tweenPosition.x = - d;
} else if(side > 0.25 && side < 0.5){ //right
tweenPosition.x = defaultStageWidth + d;
} else if(side > 0.5 && side < 0.75){ //up
tweenPosition.y = - d;
} else { //down
tweenPosition.y = defaultStageHeight + d;
}
word.tween = new Kinetic.Tween({
node: word,
duration: 4,
easing: Kinetic.Easings.Linear,
x: tweenPosition.x,
y: tweenPosition.y,
onFinish: function(){
word.clean();
callback();
}
});
word.tween.play();
}
But the problem is that click event doesn't fire on large amount of user clicks. As i think, this caused by delayed drawHit() calls inside tweening mechanism, that draws new object position before updating the hit area, so when we shoot object thinking that we hit its current position we miss because its hit area still have the same old position.
Live example
http://jsfiddle.net/hd6z21de/7/
Take a minute on shooting to see this effect in action
Solved this weird behavior by listening canvas touches and check if pointer collide some target word-rect by myself instead of using their own onclick events.
//i listen to canvas because of my app specific, you could simple listen your own layer or even document
$("canvas").bind('click', function(event){
var x = (event.pageX) / stage.scaleX(); //you don't need to divide by scale if your stage isn't scaled as mine does
var y = (event.pageY) / stage.scaleY();
var wordArray = wordGroup.getChildren();
for(var i = 0; i < wordArray.length; i++){ //go through all words and check if we shoot someone (is mouse position included in some word rect)
if(x > wordArray[i].x() &&
y > wordArray[i].y() &&
x < (wordArray[i].x() + wordArray[i].width()) &&
y < (wordArray[i].y() + wordArray[i].height())){
wordArray[i].shoot(); //shoot that word
break;
}
}
}
I am working on a simple game using Three.js on javascript. I need to use a bitmap to create the scenario. My bitmap is basically a 15x15 pixel
All I want to do is get the rgb value for every pixel on this image. This is the code I have so far:
function World()
{
var cubeMatrix = [];
this.makeScenario = function(scene)
{
var context = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.src = 'bitmap/map1.bmp';
context.drawImage(img,0,0);
var imgData = context.getImageData(0, 0, canvas.height, canvas.width);
var cube = new Cube();
cube.makeCube(1,1,MOVABLE_CUBE);
var i, j;
for(i = 0; i < MATRIX_SIZE; i++) //x
{
for(j = 0; j < MATRIX_SIZE; j++) //z
{
var rgba = getPixel( imageData, i, j);
if(rgba.r == 255 && rgba.g == 255 && rgba.b == 255) //white
{
cube.pushCube();
}
}
}
}
}
This is the code I'm using to get the pixel
function getPixel( imagedata, x, y )
{
var position = ( x + imagedata.width * y ) * 4, data = imagedata.data;
return { r: data[ position ], g: data[ position + 1 ], b: data[ position + 2 ]};
}
also added this to the html body:
<canvas id="canvas" width="15"height="15"></canvas>
I created a cube and changed its position when entering that "if" (enters when color is white), but the cube never moves at all!
I made some tests and found out that all rgb values are actually 0.
Can someone please help me with this? Thank you!
Note: this functions are on a different file from the html, but linked to it by
<script src="world.js"></script>
I want to draw image sprite using canvas.
The code not working. How to improve my code.
I have some Error.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var Game = {
draw_image: function(img, sourceX, sourceY, sourceW, sourceH, destX, destY, destW, destH){
var img = new Image(); // Create new img element
img.src = 'images/background.png'; // Set source path
img.onload = function(){
canvas.width = 1000;
canvas.height = 500;
ctx.drawImage(img, sourceX, sourceY, sourceW, sourceH, destX, destY, destW, destH);
};
}
var BACKGROUND = {
image_top: { x: 5, y: 5, w: 1280, h: 480 , dx:0 ,dy:0 ,dw:500 ,dh:500 },
image_body: { x: 5, y: 495, w: 1280, h: 480 , dx:0 ,dy:150 ,dw:500 ,dh:350},
image_bottom: { x: 5, y: 985, w: 1280, h: 480 , dx:0 ,dy:300 ,dw:500 ,dh:200 }
};
for(var n = 0 ; n < BACKGROUND.length ; n++) {
draw_image(nameImage, BACKGROUND[n].x,BACKGROUND[n].y, BACKGROUND[n].w, BACKGROUND[n].h, BACKGROUND[n].dx, BACKGROUND[n].dy, BACKGROUND[n].dw, BACKGROUND[n].dh );
}
};
To create a sprite animation it's important to know how it works.
You need your spritesheet make with pixel precision ( 1 pixel can mess up your animation ).
Like here, the character is always in the same size area, make it simple when you make your sprites.
With this you can make an object for each sprite you have like :
function Sprite(_position, _numberFrame, _framesize, _image, _duration){
this.position = _position; //Array like { x : 0, y : 0 }
this.rendersize = _rendersize; //Array like { width : 50, height : 80 }
this.framesize = _framesize; //Array like { width : 50, height : 80 }
this.image = _image; //Image object
this.chrono = new Chrono(_duration); //Explanation below
}
For more animation precision you can add a chrono who will manage the time of your animation :
function Chrono(_duration){
this.currentTime = 0;
this.lastTime = 0;
this.timeElapse = 0;
this.duration = _duration;
}
Chrono.prototype.countTime = function(){
this.currentTime = Date.now();
if(this.lastTime != 0)
this.timeElapse += this.currentTime - this.lastTime;
this.lastTime = Date.now();
if(this.timeElpase >= this.duration && this.lastTime != 0){
this.timeElapse = 0;
return TRUE;
} else {
return FALSE;
}
}
Then the function to animate your sprite may like :
Sprite.prototype.render = function(){
if(this.position.x <= this.image.width && this.chrono.countTime()){
this.position.x += this.framesize.x;
} else {
this.position.x = 0;
}
ctx.drawImage(this.image,
this.position.x, this.position.y,
this.framesize.width, this.framesize.height,
this.rendersize.width, this.rendersize.height
);
}
I hope I was clear and helpful,
Cheers
PS: Comments for question or optimisation ideas
You have to many problems with this code to make this sprite animation works. I wouldn't go to point any of the problems with your code, but I highly recommend to read a little bit about functions and variable scope before try to write this kind of code.
Another simple (and best for newbies) solution can be to use a canvas framework as EaselJS, with this you can do something like this to animate an sprite:
var data = {
images: ["images/background.png"],
frames: {width:50, height:50},
animations: {run:[0,4], jump:[5,8,"run"]}
};
var animation = new createjs.BitmapAnimation(data);
animation.gotoAndPlay("run");
I am trying to draw an isometric square with some custom code to build the pixel data up and then put it on a canvas with putImageData.
But I'm not getting the expected results, after a quick look through the raw pixel data of the canvas it seems all the pixel data I built up is getting messed with.
What I want from the below code is a red diamond on a black background. Where am i going wrong?
var Drawing = {};
Drawing.DrawIsoMetricSquare = function(cRenderContext, x, y, iWidth, cColor) {
var iHeight = iWidth / 2;
var iYPos = Math.floor(iHeight / 2) + 1;
var iXPos = 0;
var iRenderGirth = 1;
cPixelData = cRenderContext.createImageData(iWidth, iHeight);
var bExpand = true;
while (iXPos != iWidth) {
var iCurrentRenderGirth = 0;
while (iCurrentRenderGirth != iRenderGirth) {
var iY = iYPos + iCurrentRenderGirth;
//Draw first pixel then second
Drawing.ColorPixelAtPos(cPixelData.data, iXPos, iY, iWidth, cColor);
Drawing.ColorPixelAtPos(cPixelData.data, iXPos + 1, iY, iWidth, cColor);
iCurrentRenderGirth++;
}
//Move to next Render Start
iYPos = bExpand ? (iYPos - 1) : (iYPos + 1);
iXPos += 2;
iRenderGirth = bExpand ? (iRenderGirth + 2) : (iRenderGirth - 2);
bExpand &= iRenderGirth < iHeight;
}
cRenderContext.putImageData(cPixelData, x, y);
};
Drawing.XYPosToPixelPos = function(x, y, iWidth) {
return (x + y * iWidth) * 4;
};
Drawing.ColorPixelAtPos = function(cPixelData, x, y, iWidth, cColor) {
var iPixPos = Drawing.XYPosToPixelPos(x, y, iWidth);
cPixelData[iPixPos++] = cColor.r;
cPixelData[iPixPos++] = cColor.g;
cPixelData[iPixPos++] = cColor.b;
cPixelData[iPixPos] = 1; //Fixed alpha for now
};
var eCanvas = $("<canvas></canvas>");
eCanvas[0].width = 50;
eCanvas[0].height = 50;
$("#render").append(eCanvas);
var cRenderContext = eCanvas[0].getContext('2d');
cRenderContext.fillStyle = "rgba(1, 1, 1, 1)";
cRenderContext.fillRect(0, 0, 50, 50);
Drawing.DrawIsoMetricSquare(cRenderContext, 0, 0, 42, {
r: 255,
g: 0,
b: 0
});
JSFiddle example here
The problems were
a math error which you already fixed.
RGBA specifiers go from 0..255 not 0..1
You need to fill your pixel data with black opaque pixels (they are white by default).
I added a few lines of code and made a new fiddle for you.
http://jsfiddle.net/bsssq/1/
Now you should see the red diamond on the black square.