Performance Issues KineticJS - javascript

I'm quite new to canvas so I need some input.
I wan't to create a library overview with its stocks and so I have to handle about 2k+ rectangles. The problem is, the performance on drag and on scale is not very good, the fps drop below 10. Thats plain ugly, so I would appreciate some input what to do better or in other ways toe improve the performance of my (basic) script.
http://jsfiddle.net/kHGvh/13/embedded/result/
http://jsfiddle.net/kHGvh/13/

I just tried the same thing using Fabric.js, out of curiosity.
I do see noticeably better performance — http://jsfiddle.net/M7n4p/
Note that I'm using experimental "group_rewrite" branch — https://github.com/kangax/fabric.js/branches
FWIW, here's the code used to create it (just to give you comparison with Kinetic.js).
Markup:
<canvas id="c" width="1200" height="600" style="border:1px solid #ccc"></canvas>
JS:
var canvas = new fabric.Canvas('c');
var rects = [ ];
for (var i = 1; i <= 47; i++) {
for (var j = 1; j <= 42; j++) {
var rect = new fabric.Rect({
left: i*28,
top: j*18,
width: 20,
height: 10,
fill: 'green'
});
rects.push(rect);
}
}
canvas.add(new fabric.Group(rects));

I'm having the same issues as well when creating a draggable grid. However, I think there is little one can do about it.
You could think about lessening the number of cells you have. 2k+ rectangles is at least 2k+ objects that track the shape on the canvas. with the drag event happening at least 10 frames per second, you have 20k+ calculations and object accesses per second! The shear number of shapes it causing problems.

Related

Efficiently limit the area to render graphics to on an HTML5 canvas using JavaScript

I'm looking for a way to render graphics onto an HTML5 canvas using JavaScript, but I want to only render said graphics if they're inside a pre-defined mask.
I'm creating a GUI framework that can be used to easily and quickly create GUIs on an HTML5 canvas. I think that something that would be really nice to have is a way to render graphics inside an element, and make the element auto-crop the graphics so that they always stay inside of it. For example, I can make a rectangular element and animate a circular pulse inside of it, and as the circle extends past the outside of the element, those parts of he circle should just not render to keep it looking smooth and sharp. This is similar to what CSS does with overflow: hidden;
Now, I know that one option is to use a mask-like feature. For example, P5.js has mask(). However, this is very very slow. Masking a single element a single time using P5.js significantly reduces framerate, and I want to be doing this potentially hundreds of times per frame without frame drops. I know that CSS does this incredibly efficiently (from my own experience working with it), but I can't seem to think of any way to make it efficient on a canvas element.
I could do it pretty simply if it was just a rectangle, but I want to do this for any shape. For example, a circle, a star, a rectangle with rounded edges, or really any polygon at all.
How can this be done? I thought of potentially rendering to an off screen canvas (which is shrunken to the size of the element in question), then render the element onto that screen using one color (let's say the background color will be white, and the shape will be black), then rendering the image we want masked onto another off screen canvas that's the same width as our other OSC, then looping through one of their image data arrays and mapping one to the other based on whether said pixel is white or black on the mask canvas.
But........ I can't help but think that that's going to be incredibly slow for the computer to process. I assume that CSS somehow leverages the GPU to do this type of computation incredibly efficiently and that's why they get such an increase in performance. Is it possible for me to do the same or am I just dreaming?
Okay, so I have found two different means of doing this (huge thank you to #Kaiido). One method is to use ctx.clip() while one works with CanvasPattern.
This snippet shows both means in action:
<canvas id = "c" width = "400" height = "400"></canvas>
<canvas id = "c2" width = "400" height = "400"></canvas>
<script>
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "yellow";
ctx.fillRect(0,0,400,400);
ctx.beginPath();
ctx.arc(200,200,100,0,6);
ctx.clip();
ctx.beginPath();// This clears our previous arc from the path so that it doesn't render in when we `fill()`
ctx.fillStyle = "rgb(255,0,0)";
for(var i = 0;i < 20;i++){
for(var j = 0;j < 40;j++){
ctx.rect(i * 20 + j % 2 * 10,j * 10,10,10);
}
}
ctx.fill();
</script>
<script>
var canvas2 = document.getElementById("c2");
var ctx2 = canvas2.getContext("2d");
ctx2.fillStyle = "orange";
ctx2.fillRect(0,0,400,400);
var osc = new OffscreenCanvas(400,400);
var oscctx = osc.getContext("2d");
oscctx.fillStyle = "rgb(255,0,0)";
for(var i = 0;i < 20;i++){
for(var j = 0;j < 40;j++){
oscctx.rect(i * 20 + j % 2 * 10,j * 10,10,10);
}
}
oscctx.fill();
var pattern = ctx2.createPattern(osc,"no-repeat");
ctx2.fillStyle = pattern;
ctx2.arc(200,200,100,0,6);
ctx2.fill();
</script>
Which one is more efficient and better to be run hundreds of times per frame?
Another edit:
I spent about an hour messing around with it on a sandbox website, and I made this small project:
https://www.khanacademy.org/computer-programming/-/6446241383661568
There I run each one every millisecond and see how quickly each one updates to see which appears more efficient. clip() is on top while CanvasPattern is on the bottom. They both appear to be incredibly fast to me, and I feel that no matter which I chose I will have almost exactly the same results. However, clip() does still appear to be a bit faster as far as I can tell.
See for yourself and let me know what you think!

Is it possible to implement a Paint Bucket using Konva.js?

I’ve managed to implement, using konva, multiple tools that allow users to draw different shapes and patterns like: rectangle, circle, arrows, free draw, eraser, et. c.
I’m trying to achieve something like: using a paint bucket, users should be able to fill different parts of a shape, if over that shape are drawn other shapes or patterns.
Maybe this use case helps to understand better my question:
The user draws a circle.
Afterwards he draws lines over that circle so will be split in multiple areas.
The user uses now the paint bucket and tries to fill only the areas of that circle.
I’m wondering if, using konva, is possible to achieve this functionality.
Until now I've manage only to fill entire shapes, similar to this.
Update
Added images for the use case above.
1 & 2. User draws a circle and lines over it:
Using paint bucket user can fill certain areas of that circle:
Any feedback will be very welcomed.
Bad news: What you want cannot be done with Konvajs, as it is designed to work with vectorial images. Each figure is created as a whole by an equation and is "separated" of other figures (as the lines X and Y and the circle are separate in the Snippet below. It is not a raster layer. To do a paint bucket tool in vector graphics is hard.
(See Good news at the end!)
var width = window.innerWidth;
var height = window.innerHeight;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
var circle = new Konva.Circle({
x: 180,
y: 120,
radius: 50,
fill: 'red',
stroke: 'black',
strokeWidth: 4
});
var lineX = new Konva.Line({
x: 180, // 180-50
y: 120,
points: [-100, 0, 100, 0],
stroke: 'black',
strokeWidth: 4
});
var lineY = new Konva.Line({
x: 180, // 180-50
y: 120,
points: [0, -100, 0, 100],
stroke: 'black',
strokeWidth: 4
});
circle.on('click', function() {
var fill = this.fill() == 'red' ? '#00d00f' : 'red';
this.fill(fill);
layer.draw();
});
layer.add(circle);
layer.add(lineX);
layer.add(lineY);
stage.add(layer);
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
<script src="https://unpkg.com/konva#3.2.6/konva.min.js"></script>
<div id="container"></div>
Good news: But you can do it with Canvas, HTML5 and Javascript.
Here you have a good tutorial which includes a DEMO (on top of the page) and the SOURCE CODE to Create a Paint Bucket Tool in HTML5 and JavaScript
Hope this helps you!
Unless konva has a specific implementation for it that I don’t know of, this is more of an algorithmic problem.
One approach you could take if you decide to implement it on your own is something like a cell automaton. You would create one pixel somewhere in the middle, and it would grow over time (of course you don’t need to show the growth). The rules for it would be that any pixel of the specified color must colorize any pixel around it if it is the same as the average color of pixels around original point (where you clicked to fill color).
Hope this helps :)
I’ve came up with a solution: https://codesandbox.io/s/stupefied-northcutt-1y0cg.
In short, what this solution does is that when the stage is mounted, the paint bucket is setup targeting the canvas generated by konva. The pixels around the one clicked are colored using a cell automaton algorithm, as per Antoni's suggestion.
Okay, but the downside of this approach is that whenever you’re drawing a shape after paint bucket is used, the paint bucket changes get lost because (I assume) render() doesn’t know about the "vanilla" changes made in setupPaintBucket().
Another downside of this approach is that the canvas is blurry.
Sources:
Draw circle, arrow and free hand: https://codesandbox.io/s/43wzzv0l37
Vanilla Paint Program: https://codepen.io/falldowngoboone/pen/zxRXjL

How efficient is layering multiple canvases?

I've been wondering if layering canvases is actually an efficient means of increasing performance on a game.
E.g, 2 or 3 canvases of the same size on top of each other.
It's difficult to find results of testing from this, but from what I understand about drawing, if the layer on top of the others is changed, the browser would have to repaint the area to pixels anyway.
Furthermore if those canvases all had to move at the same time, you've multiplied the amount of pixels that would need to be calculated.
I was wondering how the browser handles painting canvases beneath the others if an element above changes.
Is it more efficient due to not having to call the canvas methods themselves again? Wouldn't they still need painting?
My experience is anecdotal, so you really need to test your idea to see if its better.
You're probably going to get the best performance by creating offscreen (in memory) canvases and compositing the different layers of your game with those into a single visible canvas where the game is viewed.
I'm not sure if this will be very helpful, but I'll tell you anyway.
Let's say that you've got 2 canvases and you want your game to switch between them under certain condition. This might be possible by using some HTML, CSS and JavaScript.
<canvas id="canvas1" width=500 height=500 style="border: 2px solid #00F"></canvas>
<canvas id="canvas2" width=500 height=500 style="border: 2px solid #F00"></canvas>
<button id="switcher" onclick="switchcanvas=true">Click here to switch the canvas!</button>
<style>
#canvas1 {
left: 0%;
right: 0%;
display: block;
}
#canvas2 {
left: 0%;
right: 0%;
display: none;
}
</style>
<script>
var switchcanvas = false;
var canvas1 = document.getElementById("canvas1");
var canvas2 = document.getElementById("canvas2");
function update() {
if (switchcanvas) {
if (canvas1.style.display === "block") {
canvas1.style.display = "none";
canvas2.style.display = "block";
switchcanvas = false; //if you set this to true or remove it the canvases will keep switching.
} else {
canvas1.style.display = "block";
canvas2.style.display = "none";
switchcanvas = false;
}
}
}
update();
setInterval(update, 1); //function update will update every ms, you can change that though.
</script>
I tested it and it worked. And yes, it should improve your game's performance since each canvas can have its own context.
I don't know if this is correct, but in my experience if you use two Canvases with the same frame (refresh) rate the performance improvement would be minimal, if there is any at all. You would get an improvement if the refesh rate for Canvas 1 is lower than Canvas 2. A good use case for this would be a grid and a moving object. If the grid doesn't change, you don't have to redraw it. This does not apply for the moving object, because you want to see it moving.

Fastest algorithm to draw a crossword grid in <canvas>?

I'm rendering a grid of cells, very much like the grid you find in a crossword puzzle, but using four different colors to fill each cell (not only black or white).
The grid size is about 160x120, and I need to render it as fast as possible, as it will be used to display a Cellular automaton animation.
I have tried two different approaches to render the grid:
Render each cell using something like:
var w = x + step;
var h = y + step;
canvasContext.fillStyle=cell.color;
canvasContext.fillRect(x+1,y+1,w-1,h-1);
canvasContext.strokeRect(x,y,w,h);
Render the all of cells without the border, and then render the grid lines using:
var XSteps = Math.floor(width/step);
canvasContext.fillStyle = gridColor;
for (var i = 0, len=XSteps; i<len; i++) {
canvasContext.fillRect(i*step, 0, 1, height);
}
//Similar thing for Y coord
Both algorithms perform poorly: it is slower to draw the grid than the cells in both cases. Am I missing something? How can I optimize those algorithms? Is there another way I should try?
Note: the grid moves, as the user can displace it or zoom the view.
The general question will be: what is the fastest algorithm to draw a grid of cells on a element?
The fastest way to do something is to not do it at all.
Draw your unchanging grid once on one canvas, and draw (and clear and redraw) your cellular automata on another canvas layered above (or below) that. Let the browser (in all it's native compiled optimized glory) handle dirtying and redrawing and compositing for you.
Or (better) if you are not going to change your grid size, just create a tiny image and let CSS fill it as the background.
Demo of CSS Background image to Canvas: http://jsfiddle.net/LdmFw/3/
Based on this excellent demo, here's a background image grid created entirely through CSS; with this you could change the size as desired (in whole-pixels increments).
Demo of CSS3 Grid to Canvas: http://jsfiddle.net/LdmFw/5/
If you must draw a grid, the fastest will be to just draw lines:
function drawGrid(ctx,size){
var w = ctx.canvas.width,
h = ctx.canvas.height;
ctx.beginPath();
for (var x=0;x<=w;x+=size){
ctx.moveTo(x-0.5,0); // 0.5 offset so that 1px lines are crisp
ctx.lineTo(x-0.5,h);
}
for (var y=0;y<=h;y+=size){
ctx.moveTo(0,y-0.5);
ctx.lineTo(w,y-0.5);
}
ctx.stroke(); // Only do this once, not inside the loops
}
Demo of grid drawing: http://jsfiddle.net/QScAk/4/
For m rows and n columns this requires m+n line draws in a single pass. Contrast this with drawing m×n individual rects and you can see that the performance difference can be quite significant.
For example, a 512×512 grid of 8×8 cells would take 4,096 fillRect() calls in the naive case, but only 128 lines need to be stroked in a single stroke() call using the code above.
It's really hard to help without seeing all the code to know where the performance is going, but just off the bat:
Instead of drawing a background grid using stroke, can you draw it using one call to drawImage? That will be much faster. If its truly static then you can just set a css background-image on the canvas to an image of the grid you want.
You're using fillRect and strokeRect a lot and these can probably be replaced with several calls to rect() (the path command) and only a single call to fill at the very end. So all the filled cells are rendered at once with a single filling (or stroking or both) command.
Set the fillStyle/strokeStyle as little as possible (not inside loops if you can avoid it)
You are using fill to draw the lines; it would be faster, I think, to define a path and stroke it:
canvasContext.beginPath();
var XSteps = Math.floor(width / step);
canvasContext.fillStyle = gridColor;
var x = 0;
for (var i = 0, len = XSteps; i < len; i++) {
canvasContext.moveTo(x, 0);
canvasContext.lineTo(x, height);
x += step;
}
// similar for y
canvasContext.stroke();

Implementing Layers in HTML5 Canvas

I am about to implement Photoshop-like Layers in HTML5 Canvas. Currently I have two ideas. The first and maybe the simpler idea is to have a Canvas element for each layer like:
<canvas id="layerName" width="320" height="240" style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
<canvas id="layerName" width="320" height="240" style="position: absolute; left: 0; top: 0; z-index: 2;"></canvas>
<canvas id="layerName" width="320" height="240" style="position: absolute; left: 0; top: 0; z-index: 3;"></canvas>
This way when you draw to a layer -- it actually goes to that "layer". Layers with transparent positions can be seen through to below layers (Canvases). Layer stacking is controlled with z-index property.
The second idea is to use a single Canvas element and implement some logic to handle layers like in this case:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script>
window.addEventListener('load', function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var order = 0;
function drawLayer1() {
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
}
function drawLayer2() {
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 55, 50);
}
function draw() {
ctx.clearRect(0, 0, 256, 256);
if (order === 0) {
drawLayer1();
drawLayer2();
}
else {
drawLayer2();
drawLayer1();
}
}
setInterval(draw, 250);
setInterval(function() {
order = 1 - order;
}, 200);
}, false);
</script>
</head>
<body>
<canvas id="canvas" width="256px" height="256px"></canvas>
</body>
</html>
In the above code the two layers will change stacking order every 200msec.
So, the question is that which way would be the best way? What are the pros and cons of both approaches?
If you want to use a single canvas element and have multiple layers inside it, you might want to look at my library:
https://github.com/ant512/CanvasLayers
It uses a damaged rect system to reduce the amount of repainting done every time the canvas changes, so not only do you get layers (which can be nested), but you also get optimised redraws.
Using multiple canvases should be faster, because the canvas gets drawn off-screen and then just blitted to the screen by the browser. You put the burden of switching layers on the browser, which just has to move some rectangles of graphics data around.
If you do the layering yourself, you have more control, but the burden is on the JS and the JS engine to do all the work. I would avoid this if I had a choice, but if you're going for layer effects that work on the underlying layers, this might be your only choice.
Setting the container div relative ought to have prevented that layer-overwrite issue. Try setting the position on the "occluded text" - e.g. if it's currently absolue it will obvious go in the same region as the top left of the relative stuff.
And it's probably obvious but, by the order of divs in the html you can eliminate the use of the z axis. If you want your stuff to be generic (and for other developers too), use the z axis but store a baseline to which you add your layer indices (so that baseline can be tweaked when using other code using z-axis in a problematic way).
Using jCanvas,see its layer API: http://projects.calebevans.me/jcanvas/docs/layerAPI/

Categories