Improve sprite drawing performance - javascript

I have this function to draw a sprite object (which is just an object with an array of pixel values):
this.draw = (ctx, x, y, scale) => {
let i = 0;
let startIndex, red, green, blue, alpha, currentX, currentY;
while(i < this.size.width * this.size.height){
startIndex = i * 4;
red = this.pixArray[startIndex];
green = this.pixArray[startIndex + 1];
blue = this.pixArray[startIndex + 2];
alpha = this.pixArray[startIndex + 3];
// Draw, but not if the pixel is invisible
if(alpha != 0){
ctx.fillStyle = `rgba(${red}, " + ${green} + ", " + ${blue} + ", " + ${alpha / 255.0} + ")`;
currentX = i % this.size.width;
currentY = (i - currentX) / this.size.width;
ctx.fillRect(Math.round(x + (currentX * scale)), Math.round(y + (currentY * scale)),
Math.round(scale), Math.round(scale));
}
i++;
}
}
The only thing missing from this is pixArray, which is an Uint8Array of pixel values.
However, performance is fairly abysmal. I have found that some of the performance is lost to the canvas changing state (ctx.fillStyle), but it is necessary that I modify this each iteration. Even if the fillStyle remains unchanged, the performance is still unacceptable. I realize I have the option or pre-rendering, but I wish to avoid this.

Use an ImageData to blit your array directly to a temporary canvas and then draw that to the destination canvas with the appropriate scale in a single operation:
const { width, height } = this.size;
const tCan = document.createElement('canvas');
// block scope to clean up temporary variables
{
const tCtx = tCan.getContext('2d');
const imgData = tCtx.createImageData(width, height);
tCan.width = width;
tCan.height = height;
imgData.data.set(this.pixArray);
tCtx.putImageData(imgData, 0, 0);
}
this.draw = (ctx, x, y, scale) => {
ctx.drawImage(tCan, x, y, Math.round(width * scale), Math.round(height * scale));
};

Related

Strategy to optimize javascript

I have written a javascript program that uses a genetic algorithm to recreate an image only using triangles. Here's the strategy:
generate a random pool of models, each model having an array of triangles (3 points and a color)
evaluate the fitness of each model. To do so, I compare the original image's pixel array with my model's. I use Cosine Similarity to compare arrays
keep the best models, and mate them to create new models
randomly mutate some of the models
evaluate the new pool and continue
It works quite well after some iterations as you can see here:
The problem I have, is that it is very slow, most of the time is spent getting model's pixels (converting list of triangles (color + points) to a pixel array).
Here's how I do so now:
My pixel-array is a 1D array, I need to be able to convert x,y coordinates to index:
static getIndex(x, y, width) {
return 4 * (width * y + x);
}
Then I am able to draw a point:
static plot(x, y, color, img) {
let idx = this.getIndex(x, y, img.width);
let added = [color.r, color.g, color.b, map(color.a, 0, 255, 0, 1)];
let base = [img.pixels[idx], img.pixels[idx + 1], img.pixels[idx + 2], map(img.pixels[idx + 3], 0, 255, 0, 1)];
let a01 = 1 - (1 - added[3]) * (1 - base[3]);
img.pixels[idx + 0] = Math.round((added[0] * added[3] / a01) + (base[0] * base[3] * (1 - added[3]) / a01)); // red
img.pixels[idx + 1] = Math.round((added[1] * added[3] / a01) + (base[1] * base[3] * (1 - added[3]) / a01)); // green
img.pixels[idx + 2] = Math.round((added[2] * added[3] / a01) + (base[2] * base[3] * (1 - added[3]) / a01)); // blue
img.pixels[idx + 3] = Math.round(map(a01, 0, 1, 0, 255));
}
Then a line:
static line(x0, y0, x1, y1, img, color) {
x0 = Math.round(x0);
y0 = Math.round(y0);
x1 = Math.round(x1);
y1 = Math.round(y1);
let dx = Math.abs(x1 - x0);
let dy = Math.abs(y1 - y0);
let sx = x0 < x1 ? 1 : -1;
let sy = y0 < y1 ? 1 : -1;
let err = dx - dy;
do {
this.plot(x0, y0, color, img);
let e2 = 2 * err;
if (e2 > -dy) {
err -= dy;
x0 += sx;
}
if (e2 < dx) {
err += dx;
y0 += sy;
}
} while (x0 != x1 || y0 != y1);
}
And finally, a triangle:
static drawTriangle(triangle, img) {
for (let i = 0; i < triangle.points.length; i++) {
let point = triangle.points[i];
let p1 =
i === triangle.points.length - 1
? triangle.points[0]
: triangle.points[i + 1];
this.line(point.x, point.y, p1.x, p1.y, img, triangle.color);
}
this.fillTriangle(triangle, img);
}
static fillTriangle(triangle, img) {
let vertices = Array.from(triangle.points);
vertices.sort((a, b) => a.y > b.y);
if (vertices[1].y == vertices[2].y) {
this.fillBottomFlatTriangle(vertices[0], vertices[1], vertices[2], img, triangle.color);
} else if (vertices[0].y == vertices[1].y) {
this.fillTopFlatTriangle(vertices[0], vertices[1], vertices[2], img, triangle.color);
} else {
let v4 = {
x: vertices[0].x + float(vertices[1].y - vertices[0].y) / float(vertices[2].y - vertices[0].y) * (vertices[2].x - vertices[0].x),
y: vertices[1].y
};
this.fillBottomFlatTriangle(vertices[0], vertices[1], v4, img, triangle.color);
this.fillTopFlatTriangle(vertices[1], v4, vertices[2], img, triangle.color);
}
}
static fillBottomFlatTriangle(v1, v2, v3, img, color) {
let invslope1 = (v2.x - v1.x) / (v2.y - v1.y);
let invslope2 = (v3.x - v1.x) / (v3.y - v1.y);
let curx1 = v1.x;
let curx2 = v1.x;
for (let scanlineY = v1.y; scanlineY <= v2.y; scanlineY++) {
this.line(curx1, scanlineY, curx2, scanlineY, img, color);
curx1 += invslope1;
curx2 += invslope2;
}
}
static fillTopFlatTriangle(v1, v2, v3, img, color) {
let invslope1 = (v3.x - v1.x) / (v3.y - v1.y);
let invslope2 = (v3.x - v2.x) / (v3.y - v2.y);
let curx1 = v3.x;
let curx2 = v3.x;
for (let scanlineY = v3.y; scanlineY > v1.y; scanlineY--) {
this.line(curx1, scanlineY, curx2, scanlineY, img, color);
curx1 -= invslope1;
curx2 -= invslope2;
}
}
You can see full code in action here
So, I would like to know:
is it possible to optimize this code ?
if yes, what would be the best way to do so ? Maybe there is a library doing all of the drawing stuff way better than I did ? Or by using workers ?
Thanks !
I have tested your suggestions, here's the results:
Use RMS instead of Cosine Similarity: I am not sur if the measure of similarity is better, but it is definitively not worse. It seems to run a little bit faster too.
Use UInt8Array: It surely have an impact, but does not runs a lot faster. Not slower though.
Draw to invisible canvas: Definitively faster and easier! I can remove all of my drawing functions and replace it with a few lines of code, and it runs a lot faster !
Here's the code to draw to an invisible canvas:
var canvas = document.createElement('canvas');
canvas.id = "CursorLayer";
canvas.width = this.width;
canvas.height = this.height;
canvas.display = "none";
var body = document.getElementsByTagName("body")[0];
body.appendChild(canvas);
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(0, 0, 0, 1)";
ctx.fillRect(0, 0, this.width, this.height);
for (let i = 0; i < this.items.length; i++) {
let item = this.items[i];
ctx.fillStyle = "rgba(" +item.color.r + ','+item.color.g+','+item.color.b+','+map(item.color.a, 0, 255, 0, 1)+")";
ctx.beginPath();
ctx.moveTo(item.points[0].x, item.points[0].y);
ctx.lineTo(item.points[1].x, item.points[1].y);
ctx.lineTo(item.points[2].x, item.points[2].y);
ctx.fill();
}
let pixels = ctx.getImageData(0, 0, this.width, this.height).data;
//delete canvas
body.removeChild(canvas);
return pixels;
Before those changements, my code were running at about 1.68 iterations per second.
Now it runs at about 16.45 iterations per second !
See full code here.
Thanks again !

Canvas click particle explosion effect not targeting mouse position

i'm trying to do a simple particle explosion effect so when the user clicks somewhere on the app it get's the user click position, create a canvas, create the explosion effect and then remove the canvas.
I'm totally new to canvas and got the idea from this site: canvas example
The case is it's not getting te click position right for the explosion effect, it should start with the center at the clicked area. But the farther i go from the left/top corner, farther down to the screen my effect is shown.
So here's some code:
In my app.components.ts (whose is the main file, i need it to work on every page, so i decided to put my code here) i have the following:
import { Particle } from './Particle'; // IMPORT A PARTICLE FUNCTION
// THESE ARE MY PARTICLE OPTIONS
public ANGLE: number = 90;
public SPEED: number = 8;
public PARTICLE_SIZE: number = 1;
public NUMBER_OF_PARTICLES: number = 20;
public RANGE_OF_ANGLE: number = 360;
public PARTICLE_LIFESPAN: number = 15;
public PARTICLE_COLOR: string = 'rgb(255,0,0)';
public particles: any[] = [];
public pCtxWidth: number = window.innerWidth; // not using
public pCtxHeight: number = window.innerHeight; // not using
document.addEventListener('click', (data) => {
// CREATE MY CANVAS HTML ELEMENT AND APPEND IN THE BODY
let c = document.createElement('canvas');
c.className = 'clique';
c.style.position = 'absolute';
c.style.width = String(window.innerWidth) + 'px'; //I'M USING THE WHOLE SCREEN SIZE, BUT IT DOESN'T NEEDS TO BE THAT BIG, IT CAN BE 80px
c.style.height = String(window.innerHeight) + 'px';
c.style.left = '0px';
c.style.top = '0px';
document.body.appendChild(c);
// GET MY PAGE CLICK POSITION, ALSO TRIED WITHOUT - c.offsetLeft
const x = data.pageX - c.offsetLeft,
y = data.pageY - c.offsetTop;
// CREATE MY 2DCONTEXT AND CALL THE SPARK FUNCTION
let pCtx = c.getContext("2d");
this.spark(x, y, this.ANGLE, pCtx, c);
this.smartAudio.play('click');
}, true);
// draw a new series of spark particles
spark = (x, y, angle, pCtx, c) => {
// create 20 particles 10 degrees surrounding the angle
for (var i = 0; i < this.NUMBER_OF_PARTICLES; i++) {
// get an offset between the range of the particle
let offset = Math.round(this.RANGE_OF_ANGLE * Math.random())
- this.RANGE_OF_ANGLE / 2;
let scaleX = Math.round(this.SPEED * Math.random()) + 1;
let scaleY = Math.round(this.SPEED * Math.random()) + 1;
this.particles.push(new Particle(x, y,
Math.cos((angle + offset) * Math.PI / 180) * scaleX,
Math.sin((angle + offset) * Math.PI / 180) * scaleY,
this.PARTICLE_LIFESPAN, this.PARTICLE_COLOR, pCtx));
}
this.animationUpdate(pCtx, c, x, y);
}
animationUpdate = function (pCtx, c, x, y) {
// update and draw particles
pCtx.clearRect(0, 0, x, y);
for (var i = 0; i < this.particles.length; i++) {
if (this.particles[i].dead()) {
this.particles.splice(i, 1);
i--;
}
else {
this.particles[i].update();
this.particles[i].draw(pCtx);
}
}
if (this.particles.length > 0) {
// await next frame
requestAnimationFrame(() => { this.animationUpdate(pCtx, c, x, y) });
} else {
document.body.removeChild(c);
}
}
And here is my Particle:
export function Particle(x, y, xVelocity, yVelocity, lifespan, color, pCtx) {
// set initial alpha to 1.0 (fully visibile)
this.alpha = 1.0;
// dAlpha is the amount that alpha changes per frame, randomly
// scaled around the provided particle lifespan
this.dAlpha = 1 / (Math.random() * lifespan + 0.001);
// updates the particle's position by its velocity each frame,
// and adjust's the alpha value
this.update = function() {
x += xVelocity;
y -= yVelocity;
this.alpha -= this.dAlpha;
if (this.alpha < 0)
this.alpha = 0;
}
// draw the particle to the screen
this.draw = function(pCtx: any) {
pCtx.save();
pCtx.fillStyle = color;
pCtx.globalAlpha = this.alpha;
pCtx.beginPath();
pCtx.arc(x, y, 1, 0, 2 * Math.PI, false);
pCtx.closePath();
pCtx.fill();
pCtx.restore();
}
// returns TRUE if this particle is "dead":
// i.e. delete and stop updating it if this returns TRUE
this.dead = function() {
return this.alpha <= 0;
}
}
So what an i doing wrong? How can i make the particle effect explode exactly where i clicked?
Here is an image of what i'm getting, i've clicked on the X in the top left, but the explosion occured bellow the clicked area.
Thanks in advance.
I cant see you setting the canvas resolution, you are only setting the canvas display size. This would explain a mismatch between rendering and user IO.
Try the following when you create the canvas
c.style.width = (c.width = innerWidth) + 'px';
c.style.height = (c.height = innerHeight) + 'px';
That will match the canvas resolution to the display size, that way you will be rendering at the correct pixel locations.

How to clear the canvas without interrupting animations?

I am visualising flight paths with D3 and Canvas. In short, I have data for each flight's origin and destination
as well as the airport coordinates. The ideal end state is to have an indiviudal circle representing a plane moving
along each flight path from origin to destination. The current state is that each circle gets visualised along the path,
yet the removal of the previous circle along the line does not work as clearRect gets called nearly constantly.
Current state:
Ideal state (achieved with SVG):
The Concept
Conceptually, an SVG path for each flight is produced in memory using D3's custom interpolation with path.getTotalLength() and path.getPointAtLength() to move the circle along the path.
The interpolator returns the points along the path at any given time of the transition. A simple drawing function takes these points and draws the circle.
Key functions
The visualisation gets kicked off with:
od_pairs.forEach(function(el, i) {
fly(el[0], el[1]); // for example: fly('LHR', 'JFK')
});
The fly() function creates the SVG path in memory and a D3 selection of a circle (the 'plane') - also in memory.
function fly(origin, destination) {
var pathElement = document.createElementNS(d3.namespaces.svg, 'path');
var routeInMemory = d3.select(pathElement)
.datum({
type: 'LineString',
coordinates: [airportMap[origin], airportMap[destination]]
})
.attr('d', path);
var plane = custom.append('plane');
transition(plane, routeInMemory.node());
}
The plane gets transitioned along the path by the custom interpolater in the delta() function:
function transition(plane, route) {
var l = route.getTotalLength();
plane.transition()
.duration(l * 50)
.attrTween('pointCoordinates', delta(plane, route))
// .on('end', function() { transition(plane, route); });
}
function delta(plane, path) {
var l = path.getTotalLength();
return function(i) {
return function(t) {
var p = path.getPointAtLength(t * l);
draw([p.x, p.y]);
};
};
}
... which calls the simple draw() function
function draw(coords) {
// contextPlane.clearRect(0, 0, width, height); << how to tame this?
contextPlane.beginPath();
contextPlane.arc(coords[0], coords[1], 1, 0, 2*Math.PI);
contextPlane.fillStyle = 'tomato';
contextPlane.fill();
}
This results in an extending 'path' of circles as the circles get drawn yet not removed as shown in the first gif above.
Full code here: http://blockbuilder.org/larsvers/8e25c39921ca746df0c8995cce20d1a6
My question is, how can I achieve to draw only a single, current circle while the previous circle gets removed without interrupting other circles being drawn on the same canvas?
Some failed attempts:
The natural answer is of course context.clearRect(), however, as there's a time delay (roughly a milisecond+) for each circle to be drawn as it needs to get through the function pipeline clearRect gets fired almost constantly.
I tried to tame the perpetual clearing of the canvas by calling clearRect only at certain intervals (Date.now() % 10 === 0 or the like) but that leads to no good either.
Another thought was to calculate the previous circle's position and remove the area specifically with a small and specific clearRect definition within each draw() function.
Any pointers very much appreciated.
Handling small dirty regions, especially if there is overlap between objects quickly becomes very computationally heavy.
As a general rule, a average Laptop/desktop can easily handle 800 animated objects if the computation to calculate position is simple.
This means that the simple way to animate is to clear the canvas and redraw every frame. Saves a lot of complex code that offers no advantage over the simple clear and redraw.
const doFor = (count,callback) => {var i=0;while(i < count){callback(i++)}};
function createIcon(drawFunc){
const icon = document.createElement("canvas");
icon.width = icon.height = 10;
drawFunc(icon.getContext("2d"));
return icon;
}
function drawPlane(ctx){
const cx = ctx.canvas.width / 2;
const cy = ctx.canvas.height / 2;
ctx.beginPath();
ctx.strokeStyle = ctx.fillStyle = "red";
ctx.lineWidth = cx / 2;
ctx.lineJoin = "round";
ctx.lineCap = "round";
ctx.moveTo(cx/2,cy)
ctx.lineTo(cx * 1.5,cy);
ctx.moveTo(cx,cy/2)
ctx.lineTo(cx,cy*1.5)
ctx.stroke();
ctx.lineWidth = cx / 4;
ctx.moveTo(cx * 1.7,cy * 0.6)
ctx.lineTo(cx * 1.7,cy*1.4)
ctx.stroke();
}
const planes = {
items : [],
icon : createIcon(drawPlane),
clear(){
planes.items.length = 0;
},
add(x,y){
planes.items.push({
x,y,
ax : 0, // the direction of the x axis of this plane
ay : 0,
dir : Math.random() * Math.PI * 2,
speed : Math.random() * 0.2 + 0.1,
dirV : (Math.random() - 0.5) * 0.01, // change in direction
})
},
update(){
var i,p;
for(i = 0; i < planes.items.length; i ++){
p = planes.items[i];
p.dir += p.dirV;
p.ax = Math.cos(p.dir);
p.ay = Math.sin(p.dir);
p.x += p.ax * p.speed;
p.y += p.ay * p.speed;
}
},
draw(){
var i,p;
const w = canvas.width;
const h = canvas.height;
for(i = 0; i < planes.items.length; i ++){
p = planes.items[i];
var x = ((p.x % w) + w) % w;
var y = ((p.y % h) + h) % h;
ctx.setTransform(-p.ax,-p.ay,p.ay,-p.ax,x,y);
ctx.drawImage(planes.icon,-planes.icon.width / 2,-planes.icon.height / 2);
}
}
}
const ctx = canvas.getContext("2d");
function mainLoop(){
if(canvas.width !== innerWidth || canvas.height !== innerHeight){
canvas.width = innerWidth;
canvas.height = innerHeight;
planes.clear();
doFor(800,()=>{ planes.add(Math.random() * canvas.width, Math.random() * canvas.height) })
}
ctx.setTransform(1,0,0,1,0,0);
// clear or render a background map
ctx.clearRect(0,0,canvas.width,canvas.height);
planes.update();
planes.draw();
requestAnimationFrame(mainLoop)
}
requestAnimationFrame(mainLoop)
canvas {
position : absolute;
top : 0px;
left : 0px;
}
<canvas id=canvas></canvas>
800 animated points
As pointed out in the comments some machines may be able to draw a circle if one colour and all as one path slightly quicker (not all machines). The point of rendering an image is that it is invariant to the image complexity. Image rendering is dependent on the image size but colour and alpha setting per pixel have no effect on rendering speed. Thus I have changed the circle to show the direction of each point via a little plane icon.
Path follow example
I have added a way point object to each plane that in the demo has a random set of way points added. I called it path (could have used a better name) and a unique path is created for each plane.
The demo is to just show how you can incorporate the D3.js interpolation into the plane update function. The plane.update now calls the path.getPos(time) which returns true if the plane has arrived. If so the plane is remove. Else the new plane coordinates are used (stored in the path object for that plane) to set the position and direction.
Warning the code for path does little to no vetting and thus can easily be made to throw an error. It is assumed that you write the path interface to the D3.js functionality you want.
const doFor = (count,callback) => {var i=0;while(i < count){callback(i++)}};
function createIcon(drawFunc){
const icon = document.createElement("canvas");
icon.width = icon.height = 10;
drawFunc(icon.getContext("2d"));
return icon;
}
function drawPlane(ctx){
const cx = ctx.canvas.width / 2;
const cy = ctx.canvas.height / 2;
ctx.beginPath();
ctx.strokeStyle = ctx.fillStyle = "red";
ctx.lineWidth = cx / 2;
ctx.lineJoin = "round";
ctx.lineCap = "round";
ctx.moveTo(cx/2,cy)
ctx.lineTo(cx * 1.5,cy);
ctx.moveTo(cx,cy/2)
ctx.lineTo(cx,cy*1.5)
ctx.stroke();
ctx.lineWidth = cx / 4;
ctx.moveTo(cx * 1.7,cy * 0.6)
ctx.lineTo(cx * 1.7,cy*1.4)
ctx.stroke();
}
const path = {
wayPoints : null, // holds way points
nextTarget : null, // holds next target waypoint
current : null, // hold previously passed way point
x : 0, // current pos x
y : 0, // current pos y
addWayPoint(x,y,time){
this.wayPoints.push({x,y,time});
},
start(){
if(this.wayPoints.length > 1){
this.current = this.wayPoints.shift();
this.nextTarget = this.wayPoints.shift();
}
},
getNextTarget(){
this.current = this.nextTarget;
if(this.wayPoints.length === 0){ // no more way points
return;
}
this.nextTarget = this.wayPoints.shift(); // get the next target
},
getPos(time){
while(this.nextTarget.time < time && this.wayPoints.length > 0){
this.getNextTarget(); // get targets untill the next target is ahead in time
}
if(this.nextTarget.time < time){
return true; // has arrivecd at target
}
// get time normalised ove time between current and next
var timeN = (time - this.current.time) / (this.nextTarget.time - this.current.time);
this.x = timeN * (this.nextTarget.x - this.current.x) + this.current.x;
this.y = timeN * (this.nextTarget.y - this.current.y) + this.current.y;
return false; // has not arrived
}
}
const planes = {
items : [],
icon : createIcon(drawPlane),
clear(){
planes.items.length = 0;
},
add(x,y){
var p;
planes.items.push(p = {
x,y,
ax : 0, // the direction of the x axis of this plane
ay : 0,
path : Object.assign({},path,{wayPoints : []}),
})
return p; // return the plane
},
update(time){
var i,p;
for(i = 0; i < planes.items.length; i ++){
p = planes.items[i];
if(p.path.getPos(time)){ // target reached
planes.items.splice(i--,1); // remove
}else{
p.dir = Math.atan2(p.y - p.path.y, p.x - p.path.x) + Math.PI; // add 180 because i drew plane wrong way around.
p.ax = Math.cos(p.dir);
p.ay = Math.sin(p.dir);
p.x = p.path.x;
p.y = p.path.y;
}
}
},
draw(){
var i,p;
const w = canvas.width;
const h = canvas.height;
for(i = 0; i < planes.items.length; i ++){
p = planes.items[i];
var x = ((p.x % w) + w) % w;
var y = ((p.y % h) + h) % h;
ctx.setTransform(-p.ax,-p.ay,p.ay,-p.ax,x,y);
ctx.drawImage(planes.icon,-planes.icon.width / 2,-planes.icon.height / 2);
}
}
}
const ctx = canvas.getContext("2d");
function mainLoop(time){
if(canvas.width !== innerWidth || canvas.height !== innerHeight){
canvas.width = innerWidth;
canvas.height = innerHeight;
planes.clear();
doFor(810,()=>{
var p = planes.add(Math.random() * canvas.width, Math.random() * canvas.height);
// now add random number of way points
var timeP = time;
// info to create a random path
var dir = Math.random() * Math.PI * 2;
var x = p.x;
var y = p.y;
doFor(Math.floor(Math.random() * 80 + 12),()=>{
var dist = Math.random() * 5 + 4;
x += Math.cos(dir) * dist;
y += Math.sin(dir) * dist;
dir += (Math.random()-0.5)*0.3;
timeP += Math.random() * 1000 + 500;
p.path.addWayPoint(x,y,timeP);
});
// last waypoin at center of canvas.
p.path.addWayPoint(canvas.width / 2,canvas.height / 2,timeP + 5000);
p.path.start();
})
}
ctx.setTransform(1,0,0,1,0,0);
// clear or render a background map
ctx.clearRect(0,0,canvas.width,canvas.height);
planes.update(time);
planes.draw();
requestAnimationFrame(mainLoop)
}
requestAnimationFrame(mainLoop)
canvas {
position : absolute;
top : 0px;
left : 0px;
}
<canvas id=canvas></canvas>
800 animated points
#Blindman67 is correct, clear and redraw everything, every frame.
I'm here just to say that when dealing with such primitive shapes as arc without too many color variations, it's actually better to use the arc method than drawImage().
The idea is to wrap all your shapes in a single path declaration, using
ctx.beginPath(); // start path declaration
for(i; i<shapes.length; i++){ // loop through our points
ctx.moveTo(pt.x + pt.radius, pt.y); // default is lineTo and we don't want it
// Note the '+ radius', arc starts at 3 o'clock
ctx.arc(pt.x, pt.y, pt.radius, 0, Math.PI*2);
}
ctx.fill(); // a single fill()
This is faster than drawImage, but the main caveat is that it works only for single-colored set of shapes.
I've made an complex plotting app, where I do draw a lot (20K+) of entities, with animated positions. So what I do, is to store two sets of points, one un-sorted (actually sorted by radius), and one
sorted by color. I then do use the sorted-by-color one in my animations loop, and when the animation is complete, I draw only the final frame with the sorted-by-radius (after I filtered the non visible entities). I achieve 60fps on most devices. When I tried with drawImage, I was stuck at about 10fps for 5K points.
Here is a modified version of Blindman67's good answer's snippet, using this single-path approach.
/* All credits to SO user Blindman67 */
const doFor = (count,callback) => {var i=0;while(i < count){callback(i++)}};
const planes = {
items : [],
clear(){
planes.items.length = 0;
},
add(x,y){
planes.items.push({
x,y,
rad: 2,
dir : Math.random() * Math.PI * 2,
speed : Math.random() * 0.2 + 0.1,
dirV : (Math.random() - 0.5) * 0.01, // change in direction
})
},
update(){
var i,p;
for(i = 0; i < planes.items.length; i ++){
p = planes.items[i];
p.dir += p.dirV;
p.x += Math.cos(p.dir) * p.speed;
p.y += Math.sin(p.dir) * p.speed;
}
},
draw(){
var i,p;
const w = canvas.width;
const h = canvas.height;
ctx.beginPath();
ctx.fillStyle = 'red';
for(i = 0; i < planes.items.length; i ++){
p = planes.items[i];
var x = ((p.x % w) + w) % w;
var y = ((p.y % h) + h) % h;
ctx.moveTo(x + p.rad, y)
ctx.arc(x, y, p.rad, 0, Math.PI*2);
}
ctx.fill();
}
}
const ctx = canvas.getContext("2d");
function mainLoop(){
if(canvas.width !== innerWidth || canvas.height !== innerHeight){
canvas.width = innerWidth;
canvas.height = innerHeight;
planes.clear();
doFor(8000,()=>{ planes.add(Math.random() * canvas.width, Math.random() * canvas.height) })
}
ctx.setTransform(1,0,0,1,0,0);
// clear or render a background map
ctx.clearRect(0,0,canvas.width,canvas.height);
planes.update();
planes.draw();
requestAnimationFrame(mainLoop)
}
requestAnimationFrame(mainLoop)
canvas {
position : absolute;
top : 0px;
left : 0px;
z-index: -1;
}
<canvas id=canvas></canvas>
8000 animated points
Not directly related but in case you've got part of your drawings that don't update at the same rate as the rest (e.g if you want to highlight an area of your map...) then you might also consider separating your drawings in different layers, on offscreen canvases. This way you'd have one canvas for the planes, that you'd clear every frame, and other canvas for other layers that you would update at different rate. But that's an other story.

How do I leave a trail behind my shapes in canvas?

Right now I have shapes that are created when the user spins the mouse wheel and they slowly fade away after a certain amount of time. How would I generate a trail behind each shape that follows it and also slowly disappears? Here's the code:
var canvas;
var context;
var triangles = [];
var timer;
function init() {
canvas = document.getElementById('canvas');
context = canvas.getContext("2d");
resizeCanvas();
window.addEventListener('resize', resizeCanvas, false);
window.addEventListener('orientationchange', resizeCanvas, false);
canvas.onwheel = function(event) {
handleClick(event.clientX, event.clientY);
};
var timer = setInterval(resizeCanvas, 30);
}
function Triangle(x, y, triangleColor) {
this.x = x;
this.y = y;
this.triangleColor = triangleColor;
this.vx = Math.random() * 30 - 15;
this.vy = Math.random() * 30 - 15;
this.time = 100;
}
function handleClick(x, y) {
var colors = [
[0, 170, 255],
[230, 180, 125],
[50, 205, 130]
];
var triangleColor = colors[Math.floor(Math.random() * colors.length)];
triangles.push(new Triangle(x, y, triangleColor));
for (var i = 0; i < triangles.length; i++) {
drawTriangle(triangles[i]);
}
}
function drawTriangle(triangle) {
context.beginPath();
context.moveTo(triangle.x, triangle.y);
context.lineTo(triangle.x + 25, triangle.y + 25);
context.lineTo(triangle.x + 25, triangle.y - 25);
var c = triangle.triangleColor
context.fillStyle = 'rgba(' + c[0] + ', ' + c[1] + ', ' + c[2] + ', ' + (triangle.time / 100) + ')';
context.fill();
}
function resizeCanvas() {
canvas.width = window.innerWidth - 20;
canvas.height = window.innerHeight - 20;
fillBackgroundColor();
for (var i = 0; i < triangles.length; i++) {
var t = triangles[i];
drawTriangle(t);
if (t.x + t.vx > canvas.width || t.x + t.vx < 0)
t.vx = -t.vx
if (t.y + t.vy > canvas.height || t.y + t.vy < 0)
t.vy = -t.vy
if (t.time === 0) {
triangles.splice(i, 1);
}
t.time -= 1;
t.x += t.vx;
t.y += t.vy;
}
}
function fillBackgroundColor() {
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
}
init()
<canvas id="canvas" width="500" height="500"></canvas>
Well, it's Sunday. Here's a way of doing it that works:
Add an empty array and opacity property to triangle object properties in the constructor, calling them, say, trails and alpha respectively.
Define the maximum number of ghost triangles you want in the trail. I found 3 a good value:
var MAX_GHOSTS = 3;
Make the triangle drawing function take an alpha channel value as its second parameter and remove opacity calculation from within the function itself:
function drawTriangle(triangle, alpha) { // two parameters required }
Where triangles are currently drawn in the timer callback (within the loop), calculate and update the triangle's alpha value used in the call to drawTriangle. Push a copy of selected triangle properties onto the triangle's trails array: copying freezes the x,y position. Not pushing every timer call spaces the ghost images further apart:
if( t.time%2 == 0) {
t.trails.push(
{ x: t.x, y: t.y, alpha: t.alpha, triangleColor: t.triangleColor}
);
}
Also in the timer call back, before the existing drawing loop, add a new double nested loop structure where
the outer loop retrieves the trails array of each entry in the triangles array. If the trails array length is more than MAX_GHOST, remove its first element (using splice).
the inner loop, using say j as the index, gets the next elements from the trails array, calling it crumb for example. Calculate an alpha value to make it fade quickly and draw it:
drawTriangle( crumb, (j+1)/(MAX_GHOSTS + 2) * crumb.alpha);
Hope you enjoy!

Canvas: draw lots of elements with a changing gradient (emulate angular gradient)

for this project http://biduleohm.free.fr/ledohm/ (sorry, the user interface is in french but the code is in english) I need an angular gradient but it doesn't exists in native so I've implemented it using a linear gradient on a line and I draw the lines more and more longer to form a triangle. The result is graphically OK but the speed isn't really good (1850 ms for 125 triangles). It's in the tab [RĂ©partition], it redraws if there is a keyup event on one of the inputs, don't be afraid of the apparent slowness, I've limited to maximum one redraw every 2000 ms.
Before I used a simple linear gradient on the whole triangle (but this doesn't match the reality) and the speed was OK, it draws thousands of triangles in less than a second. This function was used :
drawFrontLightForColor : function(x, y, w, h, color) {
var x2 = x - w;
var x3 = x + w;
var gradient = Distri.frontCanvas.createLinearGradient(x2, y, x3, y);
gradient.addColorStop(0, 'rgba(' + color + ', ' + Distri.lightEdgeAlpha + ')');
gradient.addColorStop(0.5, 'rgba(' + color + ', ' + (color == Distri.lightColors.cw ? Distri.lightCenterAlphaCw : Distri.lightCenterAlphaOther) + ')');
gradient.addColorStop(1, 'rgba(' + color + ', ' + Distri.lightEdgeAlpha + ')');
Distri.frontCanvas.fillStyle = gradient;
Distri.frontCanvas.beginPath();
Distri.frontCanvas.moveTo(x, y);
Distri.frontCanvas.lineTo(x2, (y + h));
Distri.frontCanvas.lineTo(x3, (y + h));
Distri.frontCanvas.lineTo(x, y);
Distri.frontCanvas.fill();
Distri.frontCanvas.closePath();
},
Then I switched to this function :
drawFrontLightForColor : function(x, y, w, h, centerColor, edgeColor) {
var ratio = w / h;
var tmpY;
var tmpW;
var x2;
var x3;
var gradient;
Distri.frontCanvas.lineWidth = 1;
for (var tmpH = 0; tmpH < h; tmpH++) {
tmpY = y + tmpH;
tmpW = Math.round(tmpH * ratio);
x2 = x - tmpW;
x3 = x + tmpW;
gradient = Distri.frontCanvas.createLinearGradient(x2, tmpY, x3, tmpY);
gradient.addColorStop(0, edgeColor);
gradient.addColorStop(0.5, centerColor);
gradient.addColorStop(1, edgeColor);
Distri.frontCanvas.beginPath();
Distri.frontCanvas.moveTo(x2, tmpY);
Distri.frontCanvas.lineTo(x, tmpY);
Distri.frontCanvas.lineTo(x3, tmpY);
Distri.frontCanvas.strokeStyle = gradient;
Distri.frontCanvas.stroke();
Distri.frontCanvas.closePath();
}
},
You can find the whole source here
I can't put the beginPath, stroke, closePath out of the loop because of the gradient which is changing every iteration (I've tried but it used the last gradient for every line (which, ironically, is identical to the first function...) which is understandable but not what I want).
I accept any advice (including redo the whole function and modify his caller to outsource some code) to improve the speed let's say 5x (ideally more).
I think you took the wrong way from the start : when doing so much changes of color, you have better operate at the pixel level.
So yes that could be with a webgl pixel shader, but you'll have to fight just to get the boilerplate running ok on all platform (or get a lib to do that for you).
And anyway there's a solution perfect for your need, and fast enough (a few ms) : use raw pixel data, update them one by one with the relevant function, then draw the result.
The steps to do that are :
- create a buffer same size as the canvas.
- iterate through it's pixel, keeping track of the x,y of the point.
- normalize the coordinates so they match your 'space'.
- compute the value for the normalized (x,y) out of all the data that you have.
- write a color (in my example i choose greyscale) out of that value.
- draw the whole buffer to canvas.
I did a jsfiddle, and here's the result with 4 data points :
fiddle is here :
http://jsfiddle.net/gamealchemist/KsM9c/3/
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var width = canvas.width,
height = canvas.height;
// builds an image for the target canvas
function buildImage(targetCanvas, valueForXY, someData) {
var width = targetCanvas.width;
var height = targetCanvas.height;
var tempImg = ctx.createImageData(width, height);
var buffer = tempImg.data;
var offset = 0;
var xy = [0, 0];
function normalizeXY(xy) {
xy[0] = xy[0] / width ;
xy[1] = xy[1] / height;
}
for (var y = 0; y < height; y++)
for (var x = 0; x < width; x++, offset += 4) {
xy[0] = x; xy[1]=y;
normalizeXY(xy);
var val = Math.floor(valueForXY(xy, someData) * 255);
buffer[offset] = val;
buffer[offset + 1] = val;
buffer[offset + 2] = val;
buffer[offset + 3] = 255;
}
ctx.putImageData(tempImg, 0, 0);
}
// return normalized (0->1) value for x,y and
// provided data.
// xy is a 2 elements array
function someValueForXY(xy, someData) {
var res = 0;
for (var i = 0; i < someData.length; i++) {
var thisData = someData[i];
var dist = Math.pow(sq(thisData[0] - xy[0]) + sq(thisData[1] - xy[1]), -0.55);
localRes = 0.04 * dist;
res += localRes;
}
if (res > 1) res = 1;
return res;
}
var someData = [
[0.6, 0.2],
[0.35, 0.8],
[0.2, 0.5],
[0.6, 0.75]
];
buildImage(canvas, someValueForXY, someData);
// ------------------------
function sq(x) {
return x * x
}
In fact the GameAlchemist's solution isn't fast or I do something really wrong. I've implemented this algo only for the top view because the front view is much more complex.
For 120 lights the top view take 100-105 ms with the old code and it take 1650-1700 ms with this code (and moreover it still lacks a few things in the new code like the color for example):
drawTopLightForColor_ : function(canvasW, canvasD, rampX, rampY, rampZ, ledsArrays, color) {
function sq(x) {
return x * x;
}
var tmpImg = Distri.topCanvasCtx.createImageData(canvasW, canvasD);
var rawData = tmpImg.data;
var ledsArray = ledsArrays[color];
var len = ledsArray.length;
var i = 0;
for (var y = 0; y < canvasD; y++) {
for (var x = 0; x < canvasW; x++, i += 4) {
var intensity = 0;
for (var j = 0; j < len; j++) {
intensity += 2 * Math.pow(
sq((rampX + ledsArray[j].x) - x) +
sq((rampZ + ledsArray[j].y) - y),
-0.5
);
}
if (intensity > 1) {
intensity = 1;
}
intensity = Math.round(intensity * 255);
rawData[i] = intensity;
rawData[i + 1] = intensity;
rawData[i + 2] = intensity;
rawData[i + 3] = 255;
}
}
Distri.topCanvasCtx.putImageData(tmpImg, 0, 0);
},
Am I doing something wrong?

Categories