d3.js parallel coordinates line thickness issue - javascript

I am trying to use different line width for different axes for parallel coordinates plot using d3.js
It works fine only if its in strictly decreasing order (for eg: lineWidth=10 for 1st axis, lineWidth=5 for 2nd axis and lineWidth=2 for 3rd axis). But if the values are like (lineWidth=10 for 1st axis, lineWidth=2 for 2nd axis and lineWidth=5 for 3rd axis) then for both the second and third axis the line thickness is 5, which is the greater value after a smaller one always overrides the smaller value. Is there any way to handle this issue? Your help is much appreciable.
Below is some code snippet which I'm currently working on.
if (i == 0) {
ctx.beginPath();
ctx.moveTo(x,y);
}
else {
if(i == 1) {
ctx.lineWidth = 1;
}
if(i == 2) {
ctx.lineWidth = 5;
}
if(i == 3) {
ctx.lineWidth = 10;
}
var cp1x = x - 0.55*(x-x0);
var cp1y = y0;
var cp2x = x - 0.45*(x-x0);
var cp2y = y;
ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
ctx.stroke();
}
For the above code the line width is 10 for all the axes.
If I use ctx.beginPath() before every if statement, then the line thickness is working fine. But unfortunately the lines drawn between axes are shifting its position (only half-lines are being drawn)
Thanks in advance.
If I use ctx.beginPath() at every if statement then this is what I'm getting

Move
ctx.beginPath();
ctx.moveTo(x,y);
before every if statement. That way each iteration will be a new path and you will move to the correct position to start each line.

Related

Set allowed drawing area in JavaScript canvas API

I'm using the JavaScript canvas API for free drawing. I'm stuck at masking the area that is allowed to be drawn on - in my example it should only be the speechbubble area.
I'm using this Vue component: https://github.com/sametaylak/vue-draw/blob/master/src/components/CanvasDraw.vue
draw(event) {
this.drawCursor(event);
if (!this.isDrawing) return;
if (this.tools[this.selectedToolIdx].name === 'Eraser') {
this.canvasContext.globalCompositeOperation = 'destination-out';
} else {
this.canvasContext.globalCompositeOperation = 'source-over';
this.canvasContext.strokeStyle = this.tools[this.selectedToolIdx].color;
}
this.canvasContext.beginPath();
this.canvasContext.moveTo(this.lastX, this.lastY);
this.canvasContext.lineTo(event.offsetX, event.offsetY);
this.canvasContext.stroke();
[this.lastX, this.lastY] = [event.offsetX, event.offsetY];
},
drawCursor(event) {
this.cursorContext.beginPath();
this.cursorContext.ellipse(
event.offsetX, event.offsetY,
this.brushSize, this.brushSize,
Math.PI / 4, 0, 2 * Math.PI
);
this.cursorContext.stroke();
setTimeout(() => {
this.cursorContext.clearRect(0, 0, this.width, this.height);
}, 100);
},
There is a built-in clip() method which sets a path as the clipping region.
var ctx=document.getElementById("cnv").getContext("2d");
ctx.lineWidth=2;
ctx.strokeStyle="red";
ctx.moveTo(0,0);
ctx.lineTo(100,100);
ctx.stroke(); // 1.
ctx.strokeStyle="black";
ctx.beginPath();
ctx.moveTo(10,10);
ctx.lineTo(100,10);
ctx.lineTo(100,60);
ctx.lineTo(30,60);
ctx.lineTo(10,80);
ctx.closePath();
ctx.stroke(); // 2.
ctx.clip(); // 3.
ctx.strokeStyle="green";
ctx.beginPath();
ctx.moveTo(0,100);
ctx.lineTo(100,0);
ctx.stroke(); // 4.
<canvas id="cnv"></canvas>
red line is drawn between 0,0 and 100,100, without clipping
bubble is drawn in black
bubble is set as clipping region
green line is drawn between 0,100 and 100,0, and correctly clipped into the bubble.
In practice you may want to have the clipping region one pixel inside the bubble, so a separate path (which is not stroke()-d, just clip()-ped), so drawing can not modify the bubble itself. If you zoom in now as it is, you will see that the green line actually overdraws the inner pixels of the bubble (linewidth is 2 pixels, and the outer one is "unharmed").
Establishing if a given point belongs to polygon's area is a quite tricky and solved problem in Computer Science.
In this concrete scenario, where you have canvas with above image set as background and 500x300 dimension you don't really need to use ray casting algorithm.
You can for example divide speech bubble area to a rectangle and a triangle, and then using event.offsetX, event.offsetY check if any given point lies inside of any of these two figures.
Code example:
isPointInArea(event) {
const x = event.offsetX;
const y = event.offsetY;
// For rectangle it is straightforward
if (x >= 60 && x <= 325 && y >= 60 && y <= 215) {
return true;
}
/* Since two sides of this triangle are parallel to canvas
It is enough to check y coordinate with one linear function of a third one
in form of y = ax + b */
if(x >= 60 && x <= 120 && y >= 215) {
const boundaryY = -0.81818181818 * x + 313.181818182;
if (y <= boundaryY) {
return true;
}
}
return false;
}
In draw function of CanvasDraw.vue
draw(event) {
if(!this.isPointInArea(event)) {
return;
}
this.drawCursor(event);
if (!this.isDrawing) return;
...
Working example on codesandbox
Result:
Edit:
As pointed out by #tevemadar you can also use simply clip() method of Canvas API. If there is nothing else you want to render (And since it is not a game, so probably that is the case), then you can just execute clip() once and you are all set. Otherwise remember to use save() method (and then of course restore(), so that you can render stuff also outside of speech bubble clipping region.

ChartJS executes a function multiple times

I'm using ChartJS to draw a line chart. The problem is that I'm trying to draw some small lines on Vertical axis to mark the axis in each 10% like this:
extendChartLine: function() {
window.Chart.plugins.register({
beforeDraw: function(chart) {
var ctx = chart.chart.ctx,
chartArea = chart.chartArea,
spacing = (chartArea.bottom - 40) /10;
for(var i = 1; i < 10; i++) {
ctx.restore();
ctx.beginPath();
ctx.moveTo(40, chartArea.bottom - i*spacing);
ctx.strokeStyle = '#333';
ctx.lineTo(47, chartArea.bottom - i*spacing);
ctx.lineWidth = 0.2;
ctx.stroke();
ctx.closePath();
ctx.save();
}
}
});
The problem is that is function is called many times causing those lines are drawing more than one time and collapsing on each others (I know that because some lines are darker than others)
I tried to use a flag variable in order to make use these codes are executing on 1 time only, but no lines are drawing on the chart.
I faced the same, if the charts have the animation option on, I think that is causing the redraw to be called multiple times

Can I optimize this canvas draw call that takes up 30% of my memory profiling?

My game has many Laser objects. mx & my represent velocity. I use the following code to draw a line from behind the Laser 2 pixels to ahead of the Laser in the direction it's going 2 pixels.
Removing the first line of the function adjusted the % of the Profiling by ~1% but I don't like the way it looks. I think I could optimize the drawing by sorting by Linewidth but that doesn't appear to get me much.
How else could I optimize this?
Laser.prototype.draw = function(client, context) {
context.lineWidth = Laser.lineWidth;
context.beginPath();
context.moveTo(this.x - this.mx * 2, this.y - this.my * 2);
context.lineTo(this.x + this.mx * 2, this.y + this.my * 2);
context.strokeStyle = this.teamColor;
context.closePath();
context.stroke();
}
Instead of multiplying things by two, why not add them?
E.g.
context.moveTo(this.x - this.mx - this.mx, this.y - this.my - this.my);
context.lineTo(this.x + this.mx + this.mx, this.y + this.my - this.my);
Testing shows that addition is an order of magnitude faster on an imac over multiplication
https://jsfiddle.net/1c85r2pq/
Dont use moveTo or lineTo as they do not use the hardware to render and are very slow. Also your code is drawing the line twice
ctx.beginPath(); // starts a new path
ctx.moveTo(x,y); // sets the start point of a line
ctx.lineTo(xx,yy); // add a line from x,y to xx,yy
// Not needed
ctx.closePath(); // This is not like beginPath
// it is like lineTo and tells the context
// to add a line from the last point xx,yy
// back to the last moveTo which is x,y
This would half the already slow render time.
A quick way to draw lines using bitmaps.
First at the start create an image to hold the bitmap used to draw the line
function createLineSprite(col,width){
var lineSprite = document.createElement("canvas");
var lineSprite.width = 2;
var lineSprite.height = width;
lineSprite.ctx = lineSprite.getContext("2d");
lineSprite.ctx.fillStyle = col;
lineSprite.ctx.fillRect(0,0,2,width);
return lineSprite;
}
var line = createLineSprite("red",4); // create a 4 pixel wide red line sprite
Or you can use an image that you load.
To draw a line you just need to create a transform that points in the direction of the line, and draw that sprite the length of the line.
// draw a line with sprite from x,y,xx,yy
var drawLineSprite = function(sprite,x,y,xx,yy){
var nx = xx-x; // get the vector between the points
var ny = yy-y;
if(nx === 0 && ny === 0){ // nothing to draw
return;
}
var d = Math.hypot(nx,ny); // get the distance. Note IE does not have hypot Edge does
// normalise the vector
nx /= d;
ny /= d;
ctx.setTransform(nx,ny,-ny,nx,x,y); // create the transform with x axis
// along the line and origin at line start x,y
ctx.drawImage(sprite, 0, 0, sprite.width, sprite.height, 0, -sprite.height / 2, d, sprite.height);
}
To draw the line
drawSpriteLine(line,0,0,100,100);
When you are done drawing all the lines you can get the default transform back with
ctx.setTransform(1,0,0,1,0,0);
The sprite can be anything, this allows for very detailed lines and great for game lasers and the like.
If you have many different colours to draw then create one sprite (image) that has many colour on it, then in the line draw function simply draw only the part of the sprite that has the colour you want. You can stretch out a single pixel to any size so you can get many colours on a small bitmap.

Cannot draw thin line in canvas?

I followed a tutorial to create a canvas graph using js. The code plotting is this:
function plotData(context, dataSet, sections, xScale) {
context.lineWidth = 1;
context.outlineWidth = 0;
context.strokeWidth = 0;
context.beginPath();
context.moveTo(0, dataSet[0]);
for (i=0; i<sections; i++) {
context.lineTo(i * xScale, dataSet[i]);
}
context.stroke();
}
I am calling this function with an array holding the points where to go.. The x value is calculated per column (xScale) and the resulting graph if i use more than 1 source of data shows up fine. Screenshot when working fine:
http://s21.postimg.org/vlc1qg9iv/Screen_Shot_2016_04_08_at_15_48_42.png
But when i remove the 2 last data lines and leave only 1 line (so when the graph has a smaller difference between graph max and min values it shows up like this:
http://s16.postimg.org/ex0fakef9/Screen_Shot_2016_04_08_at_15_44_21.png
It is in this screenshot that you can clearly see, that while it should draw a line, the line is not really a 1px line but a shape, much like a (badly) distorted line?
I am not sure if i am doing something wrong or i am plainly ignoring something? The height of the canvas is fixed and it is always calculated using:
canvas = $('#canvas-container canvas')[0];
canvas.width = $('#canvas-container').width() * 0.9;
canvas.height = $('#canvas-container').width() / 1.45;
Thanks!
Codepen of the exact effect (from the exact tutorial) can be found here:
https://codepen.io/anon/pen/JXMwBy?editors=1111
(notice there are 2 more lines of graph data i commented out and in doing so i made the Val_max and Val_min vars different to "stretch" the data in the Y line)
You are stretching the Y axis on every operation after this line:
context.scale(1,-1 * yScale);
Instead, remove the line above and multiply the y values when you draw the line in plotData().
// multiply all Y values by -yScale to flip and scale
context.moveTo(0, dataSet[0] * -yScale);
for (i=1;i<sections;i++) {
context.lineTo(i * xScale, dataSet[i] * -yScale);
}

Canvas Graph plotting data incorrectly

I have made a simple graph in a canvas but am having difficulty with two issues.
The first issue is setting the vertical axis with an appropriate scale automatically with enough room for each data value in an array. Ideally i'd like the numbers to be more rounded to the nearest million or thousand etc depending on it's actual value ranges rather than a value like 33145 as the first scale line.
Currently one value is too high for the scale and is not being drawn on the canvas because it is out of bounds.
The second issue, is the points don't seem to be plotting in their correct location, which I am unsure where my mistake was.
I made a JSFiddle as for the most part it might be a bit confusing without seeing it in action:
http://jsfiddle.net/ezttywzr/
This is how i plot my data and draw my vertical axis:
Vertical Axis:
var x = 0,
y,
range = data.max() - data.min(),
valueStep = range / 10,
// get width of largest number
margin = 3 + ctx.measureText(data.min() + (valueStep*10)).width,
pixelStep = (graph.height-40) / 10,
verticalP = pixelStep,
output;
// draw left hand values
for(var i = 0; i < 11; i++){
output = data.min() + (valueStep*i);
y = graph.height-20 - (verticalP + i*pixelStep);
ctx.fillText(output,x,y+6);
ctx.beginPath();
ctx.moveTo(margin, y);
ctx.lineTo(x2,y);
ctx.stroke();
}
Data Plotting:
var y = graph.height,
x = margin,
pos,
valueStep = (graph.width-(margin*2)) / data.length,
pixelRange = graph.height-20,
pp = range / pixelRange;
for(var i = 0; i < data.length; i++){
x += valueStep;
pos = x - (valueStep/2);
ctx.beginPath();
ctx.moveTo(x, graph.height-20);
ctx.lineTo(x, graph.height);
ctx.stroke();
ctx.fillText('Week '+(i+1),pos-(ctx.measureText('Week '+(i+1)).width/2),y);
ctx.beginPath();
ctx.arc(pos,(graph.height-20)-(verticalP+(data[i]/pp)),2,0,2*Math.PI);
ctx.stroke();
ctx.fill();
}
Nice job so far.
I made a few changes: http://jsfiddle.net/ezttywzr/2/
To get the scale I used
STEP = data.max() / NUM_HORIZONTAL_LINES
Where NUM_HORIZONTAL_LINES is the number of horizontal lines you want above the x-axis. In this case I used 10.
This means the first line will be 1 * STEP, the second will be 2 * STEP, the third will be 3 * STEP and so on..
This scale is convenient because it guarantees that the max value fits on the graph. In fact, the max value is on the top line because of the way we defined the scale.
Once we have our scale it's easy to calculate the position of the points relative to the x-axis. It's simply:
(PIXELS_PER_STEP / STEP) * VALUE
To go a step further you can do some math to round the top point of the graph up and pick a scale with that has nice round numbers.

Categories

Resources