Updating canvas values in javascript - javascript

I have a particle animation written in JavaScript using Canvas.
What i'm trying to do is to change the canvas drawing values, specifically radMax and radMin. I have written the code here for you to see: https://jsfiddle.net/u3wwxg58/
What happens now, is that when I call function f(), new particles are added with the right radMax and radMin values, instead of updating the current "drawing" with the new radMax and radMin values. Basically, what i'm trying to do is to simply make my sphere / animation larger when function f() is called.
My code for drawParticle()
var cvs = document.createElement('canvas'),
context = cvs.getContext('2d');
document.body.appendChild(cvs);
var numDots = 500,
n = numDots,
currDot,
maxRad = 100,
minRad = 90,
radDiff = maxRad-minRad,
dots = [],
PI = Math.PI,
centerPt = {x:0, y:0};
resizeHandler();
window.onresize = resizeHandler;
while(n--){
currDot = {};
currDot.radius = minRad+Math.random()*radDiff;
currDot.radiusV = 10+Math.random()*50,
currDot.radiusVS = (1-Math.random()*2)*0.005,
currDot.radiusVP = Math.random()*PI,
currDot.ang = (1-Math.random()*2)*PI;
currDot.speed = 0;
//currDot.speed = 1-Math.round(Math.random())*2;
//currDot.speed = 1;
currDot.intensityP = Math.random()*PI;
currDot.intensityS = Math.random()*0.5;
currDot.intensityO = 64+Math.round(Math.random()*64);
currDot.intensityV = Math.min(Math.random()*255, currDot.intensityO);
currDot.intensity = Math.round(Math.random()*255);
currDot.fillColor = 'rgb('+currDot.intensity+','+currDot.intensity+','+currDot.intensity+')';
dots.push(currDot);
}
function drawPoints(){
var n = numDots;
var _centerPt = centerPt,
_context = context,
dX = 0,
dY = 0;
_context.clearRect(0, 0, cvs.width, cvs.height);
var radDiff,currDot;
//draw dots
while(n--) {
currDot = dots[n];
currDot.radiusVP += currDot.radiusVS;
radDiff = currDot.radius+Math.sin(currDot.radiusVP)*currDot.radiusV;
dX = _centerPt.x+Math.sin(currDot.ang)*radDiff;
dY = _centerPt.y+Math.cos(currDot.ang)*radDiff;
//currDot.ang += currDot.speed;
currDot.ang += currDot.speed*radDiff/40000;
currDot.intensityP += currDot.intensityS;
currDot.intensity = Math.round(currDot.intensityO+Math.sin(currDot.intensityP)*currDot.intensityV);
//console.log(currDot);
_context.fillStyle= 'rgb('+currDot.intensity+','+currDot.intensity+','+currDot.intensity+')';
_context.fillRect(dX, dY, 1, 1);
console.log('draw dots');
} //draw dot
window.requestAnimationFrame(drawPoints);
}
function resizeHandler(){
var box = cvs.getBoundingClientRect();
var w = box.width;
var h = box.height;
cvs.width = w;
cvs.height = h;
centerPt.x = Math.round(w/2);
centerPt.y = Math.round(h/2);
}
drawPoints();
and my code for updating the values:
var myi = 0, timex = 20;
function f() {
numDots =500+myi*10; maxRad = 300;minRad = 200 ; n=numDots;
while(n--){
currDot = {};
currDot.radius = minRad+Math.random()*radDiff;
currDot.radiusV = 10+Math.random()*500,
currDot.radiusVS = (1-Math.random()*2)*0.005,
currDot.radiusVP = Math.random()*PI,
currDot.ang = (1-Math.random()*2)*PI;
currDot.speed = (1-Math.random()*2);
//currDot.speed = 1-Math.round(Math.random())*2;
//currDot.speed = 1;
currDot.intensityP = Math.random()*PI;
currDot.intensityS = Math.random()*0.05;
currDot.intensityO = 64+Math.round(Math.random()*64);
currDot.intensityV = Math.min(Math.random()*255, currDot.intensityO);
currDot.intensity = Math.round(Math.random()*255);
currDot.fillColor = 'rgb('+currDot.intensity+','+currDot.intensity+','+currDot.intensity+')';
dots.push(currDot);
//setTimeout(function(){n++},1000);
}
myi++;
if( myi < timex ){
setTimeout( f, 500 );
}}
f();
Picture to show what I want to do: https://postimg.org/image/9uhb3jda9/
So left one is before calling function f(), right one is when f() is called.

Function f is adding dots because the statement currDot = {}; creates a new object, and the statement dots.push(currDot);
adds it to the array of dots.
If you change it to:
currDot = dots[n];
and remove the push then it will act on the existing dots.
However, that will only work while myi is zero.
Presumably you are intending to increase the number of dots over time. Perhaps what you really want is just to completely replace the existing dots?
In which case just stick dots = []; before the while loop and leave the rest as-is.

No point iterating all the particles again just to change the size of the effect. Do it while you are rendering the particles.
From your code add the variable radiusGrowAt and increase each dot radius every time you render it. radiusGrowAt assumes the frame rate is constant and at 60fps
//just after document.body.appendChild(cvs) where you declare and define
maxRad = 20,
minRad = 10,
radDiff = maxRad-minRad,
//=================================================================
radiusGrowAt = 20 / 60, //<<== add this // grow 20 pixels every 60 frames (one second)
//=================================================================
dots = [],
PI = Math.PI,
centerPt = {x:0, y:0};
... etc
Then
//draw dots
while(n--) {
currDot = dots[n];
//=================================================================
currDot.radius += radiusGrowAt; //<<== add this line
//=================================================================
currDot.radiusVP += currDot.radiusVS;
radDiff = currDot.radius+Math.sin(currDot.radiusVP)*currDot.radiusV;
... etc

Related

Given min-value, max-value and mean, can I elegantly generate data to fit a bell curve?

Let's say I have an array of objects.
I have 3 values associated with this array: min-height, max-height and average-height.
I want to assign a height to each object so that:
No object's height is less than min-height
No object's height is greater than max-height
The mean of all objects' heights is average-height.
Essentially I am looking to generate a height distribution like this:
The heights have to be pseudo-random - that is to say, I want to be able to get a height for each object by feeding the result of a random number generator into a function and getting the height returned.
My solution at the moment is to split my range of acceptable heights (all between min-height and max-height) into a series of bins and assign a probability to each bin. Once a bin is selected, I choose a height from within that range at random.
This is not an ideal solution as it is inelegant, clunky, and produces a stepped curve as opposed to a smooth one.
Here is my current code for producing the bins:
var min_height = 10
var max_height = 100
var avg_height = 30
var scale = SCALE ()
.map_from([min_height, avg_height, max_height])
.map_to([-Math.PI, 0, Math.PI])
var range = max_height - min_height;
var num_of_bins = 10
var bin_size = range/num_of_bins;
var bins = []
var sum_of_probability = 0
while (bins.length < num_of_bins) {
var bin = {};
bin.min = min_height + (bins.length*bin_size);
bin.max = bin.min + bin_size;
bin.mid = bin.min + (bin_size/2);
bin.probability = Math.cos(scale(bin.mid))+1
sum_of_probability += bin.probability;
bins.push(bin)
}
var i;
var l = bins.length;
for (i=0; i<l; i++) {
bins[i].probability /= sum_of_probability
if (bins[i-1]) {
bins[i].cumulative_probability = bins[i-1].cumulative_probability + bins[i].probability;
}
else {
bins[i].cumulative_probability = bins[i].probability;
}
}
Essentially I would love to be able to generate pseudo-random data to roughly fit a curve in an elegant way, and I am not sure if this is possible in javascript. Let me know if you think this is do-able.
I borrowed the Gaussian "class" from here: html5 draw gaussian function using bezierCurveTo.
The stuff that's really relevant to you is the getPoints() function. Basically, given a min, max and average height, getPoints() will return an array with a smooth gaussian curve of values. You can then take those points and scale them over whatever range you would need (just multiply them).
The numSteps value of generateValues (which getPoints has hard-coded to 1000) controls how many values you get back, giving you a better "resolution". If you did something like 10, you'd have the values for something like your bar graph. Given 1000 gives a nice smooth curve.
Hope this helps.
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 200;
var Gaussian = function(mean, std) {
this.mean = mean;
this.std = std;
this.a = 1/Math.sqrt(2*Math.PI);
};
Gaussian.prototype = {
addStd: function(v) {
this.std += v;
},
get: function(x) {
var f = this.a / this.std;
var p = -1/2;
var c = (x-this.mean)/this.std;
c *= c;
p *= c;
return f * Math.pow(Math.E, p);
},
generateValues: function(start, end, numSteps = 100) {
var LUT = [];
var step = (Math.abs(start)+Math.abs(end)) / numSteps;
for(var i=start; i<end; i+=step) {
LUT.push(this.get(i));
}
return LUT;
}
};
const getPoints = () => {
const minHeight = 0;
const maxHeight = 200;
const averageHeight = 50;
const start = -10;
const end = 10;
const mean = averageHeight / (maxHeight - minHeight) * (end - start) + start;
const std = 1;
const g = new Gaussian(mean, std);
return g.generateValues(start, end, 1000);
}
const draw = () => {
const points = getPoints();
// x-axis
ctx.moveTo(0, canvas.height - 20);
ctx.lineTo(canvas.width, canvas.height - 20);
// y-axis
ctx.moveTo(canvas.width / 2, 0);
ctx.lineTo(canvas.width / 2, canvas.height);
ctx.moveTo(0, canvas.height - 20);
console.log(points);
for (let i = 0; i < points.length; i++) {
ctx.lineTo(i * (canvas.width / points.length),
canvas.height - points[i] * canvas.height - 20);
}
ctx.stroke();
};
draw();
body {
background: #000;
}
canvas {
background: #FFF;
}
<canvas></canvas>

Assigning a containers Y position In loop

I want to have my "definitionContainer"s Y position to be at the same Y position of the "questionMarkContainer".
Im not sure how to save the Y position of the questionMarkContainer and apply it to "definitionContainer" Y position when the questionMarkContaineris clicked.
I tried
definitionContainer.myNewCords = xOffsetNumberContainer;
definitionContainer.y = definitionContainer.myNewCords;
How can i accomplish the task.
function writeOutDefinitionsQuestionMarksOnRight() {
var yOffsetNumberContainer = 102;
for (var c = 0; c < randomTermsForUserSorting.length; c++) {
var questionMarkContainer = new createjs.Container();
var Highlight = new createjs.Shape();
Highlight.graphics.beginFill("hotPink").drawRoundRect(0, 0, 30, 25, 5);
var HighLightlabel = new createjs.Text("?", "10pt arial bold", "white");
HighLightlabel.textAlign = "center";
HighLightlabel.x = 15
HighLightlabel.y = 5
questionMarkContainer.addChild(Highlight, HighLightlabel);
self.stage.addChild(questionMarkContainer);
questionMarkContainer.x = 720;
questionMarkContainer.y = yOffsetNumberContainer;
questionMarkContainer.termIndex = c;
// calling a function to return the clickHandler function
// because there was some crazy stuff with using the closure of
// termIndex where the clickHandler function was always the last index.
// The 'usual' method of getting around this situation wasnt working for some reason.
var clickHandler = (function (termIndex) {
return function (e) {
var definitionContainer = new createjs.Container();
definitionContainer.myNewCords = yOffsetNumberContainer;
rect = new createjs.Shape();
rect.graphics.beginFill("DarkGreen").drawRoundRect(0, 0, 350, 150, 8);
var name = new createjs.Text(randomTermsForUserSorting[termIndex].Name, "12pt arial", "white");
name.x = 5;
name.y = 5;
name.lineWidth = 300;
var definitionText = new createjs.Text(randomTermsForUserSorting[termIndex].Definition, "10pt arial", "white");
definitionText.x = 5;
definitionText.y = 35;
definitionText.lineWidth = 330;
var xButtonRectangle = new createjs.Shape();
xButtonRectangle.graphics.beginFill("red").drawRoundRect(320, 5, 20, 20, 2);
var xTextCloseButton = new createjs.Text("X", "10pt arial", "white");
xTextCloseButton.x = 325;
xTextCloseButton.y = 7;
definitionContainer.addChild(rect, name, definitionText,xButtonRectangle, xTextCloseButton);
self.stage.addChild(definitionContainer);
definitionContainer.x = 300;
definitionContainer.y = yOffsetNumberContainer;
definitionContainer.addEventListener("click", function () {
self.stage.removeChild(definitionContainer);
});
}
})(c);
questionMarkContainer.addEventListener("click", clickHandler);
yOffsetNumberContainer += 40;
}
}
It looks like you are just adjusting a single yOffsetContainer property, which is referenced inside the click function. The click is fired later, and will use the yOffsetContainer variable, which has already been set to the number of items x 40. It does not save the loop value inside each item.
You should be able to pass the loop value as a parameter in your closure to store the loop value in the click handler:
var clickHandler = (function (termIndex, yOffset) {
return function (e) {
// OTHER CODE NOT SHOWN
definitionContainer.y = yOffset;
// MORE CODE NOT SHOWN
}
})(c, yOffsetNumberContainer);

Worst quality perspective image on canvas

I have a problem on my project.
I am developing a perspective mockup creating module for designers. Users upload images and i get them for placing in mockups with making some perspective calculations. Then users can download this image. I made all of this on clientside with js.
But there is a problem for images which are drawn on canvas with perspective calculations like this;
Sample img: http://oi62.tinypic.com/2h49dec.jpg
orginal image size: 6500 x 3592 and you can see spread edges on image...
I tried a few technics like ctx.imageSmoothingEnabled true etc.. But result was always same.
What can i do for solve this problem? What do you think about this?
edit
For more detail;
I get an image (Resolution free) from user then crop it for mockup ratio. For example in my sample image, user image was cropped for imac ratio 16:9 then making calculation with four dot of screen. By the way, my mockup image size is 6500 x 3592. so i made scale, transform etc this cropped image and put it in mockup on canvas. And then use blob to download this image to client...
Thanks.
Solved.
I use perspective.js for calculation on canvas. so I made some revisions on this js source.
If you wanna use or check source;
// Copyright 2010 futomi http://www.html5.jp/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// perspective.js v0.0.2
// 2010-08-28
/* -------------------------------------------------------------------
* define objects (name space) for this library.
* ----------------------------------------------------------------- */
if (typeof html5jp == 'undefined') {
html5jp = new Object();
}
(function() {
html5jp.perspective = function(ctxd, image) {
// check the arguments
if (!ctxd || !ctxd.strokeStyle) {
return;
}
if (!image || !image.width || !image.height) {
return;
}
// prepare a <canvas> for the image
var cvso = document.createElement('canvas');
cvso.width = parseInt(image.width) * 2;
cvso.height = parseInt(image.height) * 2;
var ctxo = cvso.getContext('2d');
ctxo.drawImage(image, 0, 0, cvso.width, cvso.height);
// prepare a <canvas> for the transformed image
var cvst = document.createElement('canvas');
cvst.width = ctxd.canvas.width;
cvst.height = ctxd.canvas.height;
var ctxt = cvst.getContext('2d');
ctxt.imageSmoothingEnabled = true;
ctxt.mozImageSmoothingEnabled = true;
ctxt.webkitImageSmoothingEnabled = true;
ctxt.msImageSmoothingEnabled = true;
// parameters
this.p = {
ctxd: ctxd,
cvso: cvso,
ctxo: ctxo,
ctxt: ctxt
}
};
var proto = html5jp.perspective.prototype;
proto.draw = function(points) {
var d0x = points[0][0];
var d0y = points[0][1];
var d1x = points[1][0];
var d1y = points[1][1];
var d2x = points[2][0];
var d2y = points[2][1];
var d3x = points[3][0];
var d3y = points[3][1];
// compute the dimension of each side
var dims = [
Math.sqrt(Math.pow(d0x - d1x, 2) + Math.pow(d0y - d1y, 2)), // top side
Math.sqrt(Math.pow(d1x - d2x, 2) + Math.pow(d1y - d2y, 2)), // right side
Math.sqrt(Math.pow(d2x - d3x, 2) + Math.pow(d2y - d3y, 2)), // bottom side
Math.sqrt(Math.pow(d3x - d0x, 2) + Math.pow(d3y - d0y, 2)) // left side
];
//
var ow = this.p.cvso.width;
var oh = this.p.cvso.height;
// specify the index of which dimension is longest
var base_index = 0;
var max_scale_rate = 0;
var zero_num = 0;
for (var i = 0; i < 4; i++) {
var rate = 0;
if (i % 2) {
rate = dims[i] / ow;
} else {
rate = dims[i] / oh;
}
if (rate > max_scale_rate) {
base_index = i;
max_scale_rate = rate;
}
if (dims[i] == 0) {
zero_num++;
}
}
if (zero_num > 1) {
return;
}
//
var step = 0.10;
var cover_step = step * 250;
//
var ctxo = this.p.ctxo;
var ctxt = this.p.ctxt;
//*** ctxt.clearRect(0, 0, ctxt.canvas.width, ctxt.canvas.height);
if (base_index % 2 == 0) { // top or bottom side
var ctxl = this.create_canvas_context(ow, cover_step);
var cvsl = ctxl.canvas;
for (var y = 0; y < oh; y += step) {
var r = y / oh;
var sx = d0x + (d3x - d0x) * r;
var sy = d0y + (d3y - d0y) * r;
var ex = d1x + (d2x - d1x) * r;
var ey = d1y + (d2y - d1y) * r;
var ag = Math.atan((ey - sy) / (ex - sx));
var sc = Math.sqrt(Math.pow(ex - sx, 2) + Math.pow(ey - sy, 2)) / ow;
ctxl.setTransform(1, 0, 0, 1, 0, -y);
ctxl.drawImage(ctxo.canvas, 0, 0);
//
ctxt.translate(sx, sy);
ctxt.rotate(ag);
ctxt.scale(sc, sc);
ctxt.drawImage(cvsl, 0, 0);
//
ctxt.setTransform(1, 0, 0, 1, 0, 0);
}
} else if (base_index % 2 == 1) { // right or left side
var ctxl = this.create_canvas_context(cover_step, oh);
var cvsl = ctxl.canvas;
for (var x = 0; x < ow; x += step) {
var r = x / ow;
var sx = d0x + (d1x - d0x) * r;
var sy = d0y + (d1y - d0y) * r;
var ex = d3x + (d2x - d3x) * r;
var ey = d3y + (d2y - d3y) * r;
var ag = Math.atan((sx - ex) / (ey - sy));
var sc = Math.sqrt(Math.pow(ex - sx, 2) + Math.pow(ey - sy, 2)) / oh;
ctxl.setTransform(1, 0, 0, 1, -x, 0);
ctxl.drawImage(ctxo.canvas, 0, 0);
//
ctxt.translate(sx, sy);
ctxt.rotate(ag);
ctxt.scale(sc, sc);
ctxt.drawImage(cvsl, 0, 0);
//
ctxt.setTransform(1, 0, 0, 1, 0, 0);
}
}
// set a clipping path and draw the transformed image on the destination canvas.
this.p.ctxd.save();
this.set_clipping_path(this.p.ctxd, [
[d0x, d0y],
[d1x, d1y],
[d2x, d2y],
[d3x, d3y]
]);
this.p.ctxd.drawImage(ctxt.canvas, 0, 0);
this.p.ctxd.restore();
}
proto.create_canvas_context = function(w, h) {
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = true;
ctx.mozImageSmoothingEnabled = true;
ctx.webkitImageSmoothingEnabled = true;
ctx.msImageSmoothingEnabled = true;
return ctx;
};
proto.set_clipping_path = function(ctx, points) {
ctx.beginPath();
ctx.moveTo(points[0][0], points[0][1]);
for (var i = 1; i < points.length; i++) {
ctx.lineTo(points[i][0], points[i][1]);
}
ctx.closePath();
ctx.clip();
};
})();
The problem is (most likely, but no code shows so..) that the image is actually too big.
The canvas typically uses bi-linear interpolation (2x2 samples) rather than bi-cubic (4x4 samples). That means if you scale it down a large percentage in one chunk the algorithm will skip some pixels that otherwise should have been sampled, resulting in a more pixelated look.
The solution do is to resize the image in steps, ie. 50% of itself repeatably until a suitable size is achieved. Then use perspective calculations on it. The exact destination size is something you need to find by trial and error, but a good starting point is to use the largest side of the resulting perspective image.
Here is one way to step-down rescale an image in steps.

Scroll along path Paper.js

Basically I want to scroll a object along path. I've seen several threads looking for similar solution not using paper.js but i was wondering if this possible with paper.js. Or can someone give me a working jsfiddle of object follow svg curve because I couldn't get any thing to work. I ultimately want to have a chain of divs follow the path.
// vars
var point1 = [0, 100];
var point2 = [120, 100];
var point3 = [120, 150];
// draw the line
var path = new Path();
path.add(new Point(point1), new Point(point2), new Point(point3));
path.strokeColor = "#FFF";
path.closed = true;
// draw the circle
var circle = new Path.Circle(0,100,4);
circle.strokeColor = "#FFF";
// target to move to
var target = point2;
// how many frame does it take to reach a target
var steps = 200;
// defined vars for onFrame
var dX = 0;
var dY = 0;
// position circle on path
circle.position.x = target[0];
circle.position.y = target[1];
function onFrame(event) {
//check if cricle reached its target
if (Math.round(circle.position.x) == target[0] && Math.round(circle.position.y) == target[1]) {
switch(target) {
case point1:
target = point2;
break;
case point2:
target = point3;
break;
case point3:
target = point1;
break;
}
// calculate the dX and dY
dX = (target[0] - circle.position.x)/steps;
dY = (target[1] - circle.position.y)/steps;
}
// do the movement
//circle.position.x += dX;
//circle.position.y += dY;
}
Here is the jsfiddle:
http://jsfiddle.net/J9xgY/12/
Thanks!
You can find a point along a path with path.getPointAt(offset) where offset is measured in points along the length of the path. If you can calculate the position of a slider along its track, you can multiply that by the path.length to get an offset.
You can do this with an HTML slider or with a canvas element, as shown here:
// vars
var point1 = [0, 100];
var point2 = [120, 100];
var point3 = [120, 150];
// draw the line
var path = new Path();
path.add(new Point(point1), new Point(point2), new Point(point3));
path.strokeColor = "#FFF";
path.closed = true;
// draw the circle
var circle = new Path.Circle(0,100,4);
circle.strokeColor = "#FFF";
// slider
var sliderLine = new Path(new Point(10,30.5), new Point(210, 30.5));
sliderLine.strokeColor = '#FFF';
var sliderKnob = new Path.Circle(new Point(10,30.5), 5);
sliderKnob.fillColor = '#FFF';
var sliderHit = false;
function onMouseDown(event) {
if (event.item == sliderKnob) sliderHit = true;
}
function onMouseDrag(event) {
if (sliderHit === true) {
if (event.point.x > 10 && event.point.x < 210) {
sliderKnob.position.x = event.point.x;
}
else if (event.point.x < 11) {
sliderKnob.position.x = 10;
}
else if (event.point.x > 209) {
sliderKnob.position.x = 210;
}
// Get offset and set circle position
var percent = ( sliderKnob.position.x - 10 ) / 200;
circle.position = path.getPointAt(path.length * percent);
}
}
function onMouseUp(event) {
sliderHit = false;
}
jsfiddle: http://jsfiddle.net/J9xgY/13/
Click and drag the filled circle along the line to move the circle along the triangle.

Free memory on FPS system

I start on KineticJS (and on Canvas) and i'm creating a small game for learn...
Right now, I have just 2 layers :
First with a map composed by Kinetic.Image
Second with the last time who game as draw.
I want refresh display X time per second but after 20 or 30 times the game are really slow.. And it's the same when I flood event click ( who launch the draw function too)...
Moreover, i can see in the second layer : the old text are never clean, the new are added on top... :/
var stage;
var layers = {};
var CANEVAS_WIDTH = 800;
var CANEVAS_HEIGHT = 600;
var MAP_WIDTH = 10;
var MAP_HEIGHT = 10;
var MAPPING_WIDTH = 150;
var MAPPING_HEIGHT = 88;
var LEFT_X = 0;
var LEFT_Y = MAP_WIDTH*MAPPING_HEIGHT/2;
var TOP_X = MAP_WIDTH/2*MAPPING_WIDTH;
var TOP_Y = 0;
var VIEW_X = 0;
var VIEW_Y = 0;
var CURSOR_X = 6;
var CURSOR_Y = 0;
var images = {};
function loadImages(sources, callback)
{
var loadedImages = 0;
var numImages = 0;
// get num of sources
for (var src in sources)
numImages++;
for (var src in sources)
{
images[src] = new Image();
images[src].onload = function(){
if (++loadedImages >= numImages)
callback();
};
images[src].src = sources[src];
}
}
function getMouseInfo(mousePos)
{
var info = {screen_x : mousePos.x,
screen_y : mousePos.y,
mouse_x : mousePos.x+VIEW_X,
mouse_y : mousePos.y+VIEW_Y-LEFT_Y,
onMap : 0,
map_x : -1,
map_y : -1};
map_x = -(info.mouse_y - ((LEFT_Y * info.mouse_x) / TOP_X)) / MAPPING_HEIGHT;
map_y = -(-info.mouse_y - ((LEFT_Y * info.mouse_x) / TOP_X)) / MAPPING_HEIGHT;
if(map_x >= 0 && map_x < MAP_WIDTH && map_y >= 0 && map_y < MAP_HEIGHT)
{
info.map_y = parseInt(map_y);
info.map_x = parseInt(map_x);
info.onMap = 1;
}
return info;
}
function draw()
{
drawMap();
drawFPS();
stage.add(layers.mapLayer);
stage.add(layers.fpsLayer);
}
function drawFPS()
{
layers.fpsLayer.clear();
var fps = new Kinetic.Shape(function(){
var date = new Date();
var time = date.getTime();
var context = this.getContext();
context.beginPath();
context.font = "12pt Calibri";
context.fillStyle = "red";
context.fillText("FPS : "+time, 10, 20);
});
layers.fpsLayer.add(fps);
}
function drawMap()
{
var x=0,y=0;
layers.mapLayer.clear();
var s = new Kinetic.Shape(function(){
var context = this.getContext();
context.beginPath();
context.rect(0, 0, CANEVAS_WIDTH, CANEVAS_HEIGHT);
context.fillStyle = "#000";
context.fill();
context.closePath();
});
layers.mapLayer.add(s);
for(x=0; x<MAP_WIDTH; x++)
for(y=0;y<MAP_HEIGHT; y++)
{
var img = new Kinetic.Image({
image: ((x==CURSOR_X && y==CURSOR_Y)?images.testMapCursor:images.testMap)
});
img.x = x*MAPPING_WIDTH/2 + y*MAPPING_WIDTH/2 - VIEW_X;
img.y = (MAP_WIDTH-1)*MAPPING_HEIGHT/2 - x*MAPPING_HEIGHT/2 + y*MAPPING_HEIGHT/2 - VIEW_Y;
layers.mapLayer.add(img);
}
}
function changeCursorPosition(cursor_x, cursor_y)
{
CURSOR_X = cursor_x;
CURSOR_Y = cursor_y;
draw();
}
function initStage()
{
layers.mapLayer = new Kinetic.Layer();
layers.fpsLayer = new Kinetic.Layer();
draw();
}
/*
* INIT
*/
window.onload = function(){
stage = new Kinetic.Stage("container", <?=CANEVAS_WIDTH;?>, <?=CANEVAS_HEIGHT;?>);
stage.on("mousemove", function(){
var mouseInfo = getMouseInfo(stage.getMousePosition());
if(mouseInfo.onMap)
document.body.style.cursor = "pointer";
else
document.body.style.cursor = "default";
});
stage.on("mousedown", function(){
var mouseInfo = getMouseInfo(stage.getMousePosition());
if(mouseInfo.onMap)
changeCursorPosition(mouseInfo.map_x, mouseInfo.map_y);
});
var sources = {
testMap : "testMap.png",
testMapCursor : "testMapCursor.png"
};
loadImages(sources, initStage);
};
Sorry, my english are realy bad.
Thank all.
I know someone who is trying out KineticJS. I haven't used it myself, so I apologize that I cannot provide more specific help.
Unfortunately, it is very difficult to get good performance with canvas, and it depends greatly on the browser. Last I checked, Opera 12 and IE 9 performed significantly faster than other browsers, since their 2D rendering is 3D accelerated (using OpenGL and Direct3D, respectively)
I am not sure if this applies to KineticJS, but one technique you can use to improve performance with canvas is to use multiple canvas elements, and transform their positions rather than blitting on a single surface.
I've been pretty happy with the results I've gotten using Jeash, which is wired into NME's command-line tools. The development is similar to working with Flash, but it will create an HTML5 Canvas application using your code. The same application will also be able to publish to Windows, Mac, Linux, iOS, Android, webOS and Flash, as either native C++ and OpenGL, or as SWF bytecode. This gives you a lot of options for providing the best experience for each user.
http://www.haxenme.org

Categories

Resources