How to paint over a complex object - javascript

I do have a fairly complex figure painted on canvas. (~ 1000 polygons). The repainting time for all of them is about 1 sec (very slow). Now I need to let user move over that figure and display a vertical and horizontal lines (cross hairs) from under mouse position. What is the best technique to paint only those 2 lines without going over all polygons and repaint everything at every mouse move.
Thx

This answer is broken.
You want to draw lines and move them without touching the underlying painting.
In the good old days, the method used was to paint with xor composition on top of the drawing, and draw the same pattern (here it would be lines) the same way at the same location to remove it from the screen, again without touching the real painting.
I tried to use this method with the code below to test it out, but it doesn't seem to work. Hopefully, someone with a better knowledge of canvas and js will come forth and fix things up.
function onmousemove(e){
// firt run
var tcanvas = document.getElementById("testCanvas");
var tcontext = tcanvas.getContext("2d");
var pos = {x : e.clientX, y : e.clientY,
w : tcanvas.width, h : tcanvas.height };
var comp = tcontext.globalCompositeOperation;
var paintline = function (p){
tcontext.save();
tcontext.lineWidth = 1;
tcontext.globalCompositeOperation = 'xor';
tcontext.fillStyle = "#000000";
tcontext.moveTo(0,p.y);
tcontext.lineTo(p.w,p.y);
tcontext.moveTo(p.x,0);
tcontext.lineTo(p.x,p.h);
tcontext.stroke();
tcontext.restore();
};
tcontext.save();
paintline(pos);
tcontext.restore();
var next = function(e){
var comp = tcontext.globalCompositeOperation;
paintline(pos);
pos = {x : e.clientX, y : e.clientY,
w : tcanvas.width, h : tcanvas.height };
paintline(pos);
};
document.onmousemove = next;
}
(function draw_stuff(){
// setup canvas
var tcanvas = document.getElementById("testCanvas");
var tcontext = tcanvas.getContext("2d");
// draw square
tcontext.fillStyle = "#FF3366";
tcontext.fillRect(15,15,70,70);
// set composite property
tcontext.globalCompositeOperation = 'xor';
// draw text
tcontext.fillStyle="#0099FF";
tcontext.font = "35px sans-serif";
tcontext.fillText("test", 22, 25);
// draw circle
tcontext.fillStyle = "#0099FF";
tcontext.beginPath();
tcontext.arc(75,75,35,0,Math.PI*2,true);
tcontext.fill();
document.onmousemove = onmousemove;
})();
Also, there are problem with compositing depending on the browser.

Related

Maximum movement speed sprite PIXI.js

I'm writing a simple game in which a user can move around a sprite. By clicking the stage, the sprite moves towards that location. The problem I'm facing is that I want to set a speed for this sprite. I do not know the values the user is going to click. I can't think of a way in which the sprite's speed is always the same.
The thing with PIXI.js is that you can set the x and y movement speed of the sprite. I want the result of those movement speeds to always be the same, for example 5. So if the sprite moves down, the y-speed would be 5. When the sprite is moving diagonally, the diagonal speed should be 5. I currently use this script, but the solution I came up with does not completely work, as the speed differs for each time I click.
Does anyone have any idea how to solve this problem?
var Container = PIXI.Container,
autoDetectRenderer = PIXI.autoDetectRenderer,
loader = PIXI.loader,
resources = PIXI.loader.resources,
Sprite = PIXI.Sprite;
var stage = new PIXI.Container(),
renderer = PIXI.autoDetectRenderer(1000, 1000);
document.body.appendChild(renderer.view);
PIXI.loader
.add("rocket.png")
.load(setup);
var rocket, state;
function setup() {
//Create the `tileset` sprite from the texture
var texture = PIXI.utils.TextureCache["animal.png"];
//Create a rectangle object that defines the position and
//size of the sub-image you want to extract from the texture
var rectangle = new PIXI.Rectangle(192, 128, 32, 32);
//Tell the texture to use that rectangular section
texture.frame = rectangle;
//Create the sprite from the texture
rocket = new Sprite(texture);
rocket.anchor.x = 0.5;
rocket.anchor.y = 0.5;
rocket.x = 50;
rocket.y = 50;
rocket.vx = 0;
rocket.vy = 0;
//Add the rocket to the stage
stage.addChild(rocket);
document.addEventListener("click", function(){
x = event.clientX - rocket.x;
y = event.clientY - rocket.y;
rocket.vmax = 5;
var total = Math.abs(x) + Math.abs(y);
var tx = x/total;
var ty = y/total;
rocket.vx = tx*rocket.vmax;
rocket.vy = ty*rocket.vmax;
});
state = play;
gameLoop();
}
function gameLoop() {
//Loop this function at 60 frames per second
requestAnimationFrame(gameLoop);
state();
//Render the stage to see the animation
renderer.render(stage);
}
function play(){
rocket.x += rocket.vx;
rocket.y += rocket.vy;
}
How about this? This would normalize x and y.
var total = Math.Sqrt(x * x + y * y);
and it looks x and y are missing 'var'.
var x = event.clientX - rocket.x;
var y = event.clientY - rocket.y;

Animating a curved motion of an object with svg.js

I want to animate a curved motion (no rotation) of an object by using svg.js. But I can't find any easy solution for this problem. I wrote two little functions which work fine, but it isn't working like a normal animation, and it doesn't run perfectly in the background.
I would prefer some solution like this:
var draw = SVG("drawing").size(500,500);
var rect = draw.rect(50,50);
rect.animate().curvedmove(100,100);
The two functions I made:
function animateJump(object,start,end,ampl,y,i=0){
var speed = 25;
var pos = 0;
pos = start+i*((end-start)/speed);
object.animate(1).move(pos,y+bounceFunction(start,end,ampl,pos));
if (i <= speed){
animateJump(object,start,end,ampl,y,i+1)
}
}
function bounceFunction(a,b,c,x){
return -1 * (x-a)*(x-b) * c * (4/((a-b)*(b-a)));
}
Is there some easy solution?
Thanks for any help!
The animate method establish a new animation context in which runs the timer you specified (1 sec by default). So if you do el.animate().move(100,100) the element will move to position 100,100 in 1 second.
However, if you want to use your own function you need to listen to the during event which gives you the current position from 0-1 in time.
el.animate().during(function(pos, morphFn, easedPos) {
this.move(pos, bounceFunction(pos))
})
Note that pos is a value between 0 and 1 so setting it directly as coordinate does not make that much sense. You need to figure our the start and end value of the move and calculate it yourself (or use the morphFn like morphFn(start, end))
Example:
var startX = 100
var endX = 300
var startY = 100
var endY = 300
el.animate().during(function(pos, morphFn, easedPos) {
var x = morphFn(startX, endX)
var y = SVG.morph(bounceFunction(pos))(startY, endY)
this.move(x, y)
})
the morphFn is by default bound to the current position. So if you have your own position (like when using your custom bounce function) you need to create a new morph function which you can do with the SVG.morph method. This method expects a position and gives back a morph function bound to this positon.
So this would be the same:
var x = SVG.Morph(pos)(startX, endX)
var y = SVG.Morph(bounceFunction(pos))(startY, endY)

how to animate drawing lines on canvas

I have created some lines connecting with each other on canvas. Now I want to animate these lines while drawing on canvas.
Can anyone please help?
here is my code and fiddle URL:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.moveTo(0,0,0,0);
ctx.lineTo(300,100);
ctx.stroke();
ctx.moveTo(0,0,0,0);
ctx.lineTo(10,100);
ctx.stroke();
ctx.moveTo(10,100,0,0);
ctx.lineTo(80,200);
ctx.stroke();
ctx.moveTo(80,200,0,0);
ctx.lineTo(300,100);
ctx.stroke();
http://jsfiddle.net/s4gWK/1/
I understand that your want the lines to extend incrementally along the points in your path using animation.
A Demo: http://jsfiddle.net/m1erickson/7faRQ/
You can use this function to calculate waypoints along the path:
// define the path to plot
var vertices=[];
vertices.push({x:0,y:0});
vertices.push({x:300,y:100});
vertices.push({x:80,y:200});
vertices.push({x:10,y:100});
vertices.push({x:0,y:0});
// calc waypoints traveling along vertices
function calcWaypoints(vertices){
var waypoints=[];
for(var i=1;i<vertices.length;i++){
var pt0=vertices[i-1];
var pt1=vertices[i];
var dx=pt1.x-pt0.x;
var dy=pt1.y-pt0.y;
for(var j=0;j<100;j++){
var x=pt0.x+dx*j/100;
var y=pt0.y+dy*j/100;
waypoints.push({x:x,y:y});
}
}
return(waypoints);
}
Then you can use requestAnimationFrame to animate each incremental line segment:
// calculate incremental points along the path
var points=calcWaypoints(vertices);
// variable to hold how many frames have elapsed in the animation
// t represents each waypoint along the path and is incremented in the animation loop
var t=1;
// start the animation
animate();
// incrementally draw additional line segments along the path
function animate(){
if(t<points.length-1){ requestAnimationFrame(animate); }
// draw a line segment from the last waypoint
// to the current waypoint
ctx.beginPath();
ctx.moveTo(points[t-1].x,points[t-1].y);
ctx.lineTo(points[t].x,points[t].y);
ctx.stroke();
// increment "t" to get the next waypoint
t++;
}
EDIT: I misunderstood your original post. For your situation you do not need to clear the previous animation, only when the animation is complete to start it all over.
jsfiddle : http://jsfiddle.net/Grimbode/TCmrg/
Here are two websites that helped me understand how animations work.
http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/
In this article William speaks sprite animations, which of course isn't what you are interested in. What is interesting is that he uses a recursive loop function created by Paul Irish.
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
This function will attempt to spin 60 times per second (so essentially at 60 fps).
(function() {
var lastTime = 0;
var vendors = ['webkit', 'moz'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
So the big question is, how does this work? You pretty much just need to do this:
function gameLoop () {
window.requestAnimationFrame(gameLoop);
renderLine();
}
var counter = 0;
var old_position = {x: 0, y: 0};
var new_position = {x: 0, y: 0};
var width = 10;
var height = 10;
function renderLine(){
/* Here you clear the old line before you draw the new one */
context.clearRect(old_position.x, old_position.y, width, height)
/* you update your new position */
new_position = {x: 100, y: 200};
/* Here you call your normal moveTo and lineTo and stroke functions */
/* update old position with the nwe position */
old_position = new_position;
}
After this step, your question will probably like. "Ok, I have some kind of animation going on, but I don't want my line animation to spin at 60 fps". If you read williams post he uses "ticks".
The websites I linked do a much better job at explaining than I could. I suggest you read up on them. [= I had fun reading them.
AND: Here is your jfiddle :)
http://jsfiddle.net/Grimbode/TCmrg/
The idea is to draw and draw and draw several different lines in a loop to have the illusion that it's "animating". But that is the concept of animation anyway.
So determine what animation you want to do, and find out a way you can draw each frame in a loop.
That's the concept anyway. But I'd advise you use libraries for this.
Fabric.js (http://fabricjs.com/) and KineticJS (http://kineticjs.com/) are the libraries/frameworks I'd point you to.

html canvas a line following mouse

So i want to make a line follow mouse and on click to draw that line, i need this for drawing polygons. My idea was to draw a line every time mouse moves but then it makes mess with a lot of lines, so i decided to draw over old lines after mouse moves with white lines to clean up and so that there would be only one line that goes from a point of last clicked spot to current mouse location.My jsFiddle for this. but it doesn't work the way i want yes i draws polygons on clicking but there is no line following the mouse so i can't see what line I'm drawing. I don't see where is it wrong ? Maybe there is some ready solution that i didn't find ? Mycode :
var polygonX = [];
var polygonY = [];
var lineReady = 0;
var whileLineX;
var whiteLineY;
$("#body").bind('mousemove', function (ev) {
if (lineReady >= 2) {
var context;
//clear old lines
if (whiteLineX !== null && whiteLineY !== null) {
context = $("#canvas")[0].getContext('2d');
context.moveTo(polygonX[lineReady - 1], polygonY[lineReady - 1]);
context.lineTo(whiteLineX, whiteLineY);
context.strokeStyle = '#ffffff';
context.stroke();
}
//draw a new line
context = $("#canvas")[0].getContext('2d');
var offset = $('#body').offset();
var x = ev.clientX - offset.left;
var y = ev.clientY - offset.top;
context.beginPath();
context.moveTo(polygonX[lineReady - 1], polygonY[lineReady - 1]);
context.strokeStyle = '#000000';
context.lineTo(x, y);
context.stroke();
whileLineX = x;
whiteLineY = y;
}
});
$("#body").bind('click', function (ev) {
var offset = $('#body').offset();
var x = ev.clientX - offset.left;
var y = ev.clientY - offset.top;
polygonX
.push(x);
polygonY.push(y);
lineReady++;
if (lineReady >= 2) {
var context = $("#canvas")[0].getContext('2d');
context.beginPath();
context.moveTo(polygonX[lineReady - 2], polygonY[lineReady - 2]);
context.lineTo(polygonX[lineReady - 1], polygonY[lineReady - 1]);
context.stroke();
}
});`
The best way to do this is to use a bit of animation.
Everytime you draw a line, push its coordinates (first point and last point) in an array. Then draw your array at every animation loop(check out this link which will explain you how to animate)
. Then you'll want to draw a single line, say colored in red, from the last point of the last line of the array where you're pushing lines to your mouse position.
Doing it this way will allow you to have a red line following your mouse at all times, giving you a "preview" of a line.
Algo-wise it would look like:
var arrayOflines = [];
canvas.onclick ->
var coordinates = mouseposition()
arrayOfLines.push(coordinates)
function mouseposition(){
returns x and y of your mouse on the canvas
}
function draw(array){
loop through array
draw line from array[0] to array[1], then from array[1] to array[2] on canvas
}
function drawPreview(){
draw line from last point of arrayOflines to mouseposition;
}
//so here we are:
function animationloop{
erase your canvas
draw(arrayOfLines); //draw your array
drawPreview(); //draw your 'preview' line
requestAnimationFrame(animationloop); //animate
}
Doing things this way will allow you to achieve a clean result.

How to get the position of a click event relative to its layer in KineticJS?

I'm developing a hex-grid strategy game in HTML5, and since it becomes complicated to add more buttons to UI, I'm rewriting my code using KineticJS to draw the canvas.
In my game, there is a minimap, and a rectangle in it showing the position of player's camera. When the player clicks on the minimap, the center of his camera will be set to the position he clicked. My original code does not use any external library, and it looks like this:
this.on('click', function(event){
var canvas = document.getElementById('gameCanvas');
var x = event.pageX - canvas.offsetLeft;
var y = event.pageY - canvas.offsetTop;
camera.setPos( // calculate new position based on x and y....);
}
})
So basically what I want is the POSITION OF CLICK EVENT RELATIVE TO THE CANVAS. Since now KineticJS takes control of the canvas, and it does not let me set canvas id, I can't use getElementById to choose my canvas anymore. Is there another way to do it?
There might be some way I did not figure out that can set the canvas id, but I'm expecting a more elegent solution, idealy through KineticJS API.
Thanks.
To get the mouse position on the stage (canvas), you can use:
var mouseXY = stage.getPointerPosition();
var canvasX = mouseXY.x;
var canvasX = mouseXY.y;
You can get the mouse position inside a shape click the same way:
myShape.on('click', function() {
var mouseXY = stage.getPointerPosition();
var canvasX = mouseXY.x;
var canvasY = mouseXY.y;
});
Good question, and I think what you are looking for is getAbsolutePosition().
The following is useful things to know from my experience.
getPosition()
node x/y position relative to parent
if your shape is in layer, x/y position relative to layer
if your shape is in group, x/y position relative to group
getParent()
To know what parent node is
getX()
x position relative to parent
getY()
y position relative to parent
getAbsolutePosition()
absolute position relative to the top left corner of the stage container div
Few more useful things,
getScale()
if your stage is zoomed in or out, better to know this.
Everything is here in document, http://kineticjs.com/docs/symbols/Kinetic.Node.php
This is an old question, but as I can see, the best answer does not take into account the rotation.
So here it is my solution based on Kinetic v5.1.0. who take into account all transformation.
var myStage = new Kinetic.Stage();
var myShape = new Kinetic.Shape(); // rect / circle or whatever
myShape.on('click', function(){
var mousePos = myStage.getPointerPosition();
var p = { x: mousePos.x, y: mousePos.y }; // p is a clone of mousePos
var r = myShape.getAbsoluteTransform().copy().invert().point(mousePos);
// r is local coordinate inside the shape
// mousePos is global coordinates
})
I found out the best way to do it is...
var bgxy = bg.getAbsolutePosition();
var x = event.pageX - stage.getContainer().offsetLeft - bgxy.x;
var y = event.pageY - stage.getContainer().offsetTop - bgxy.y;
You should use event.layerX and event.layerY :
this.on('click', function(event){
var canvas = document.getElementById('gameCanvas');
var x = event.layerX;
var y = event.layerY;
camera.setPos( // calculate new position based on x and y....);
}
})

Categories

Resources