Draw rectangle on HTML 5 / Javascript Teechart - javascript

I need to draw vertical and horizontal rectangle / bands (like in Gantt charts) on the HTML 5 / JavaScript Tee charts.
I could draw a rectangle using the Bar series as below but I want the rectangle to float on a particular XY cor-ordinate rather standing from the x axis.
var series1 = new Tee.Bar();
series1.data.values = [30000];
//alert(" openValues[y] "+ openValues[y] + " closeValues[y] "+ closeValues[y] );
series1.data.x = [ (openValues[y] + closeValues[y]) /2 ];
series1.format.shadow.visible = false;
series1.format.lineCap = "round";
series1.format.stroke.fill = "#D3D3D3";
series1.format.stroke.size = .5;
series1.colorEach = "auto";
series1.format.join = "round";
series1.format.cap = "square";
series1.format.fill="#F8F8FF";
series1.barSize=100000;
//series1.format.transparent =1;
series1.color = "silver";
series1.marks.visible = false;
//series1.hover.shadow =false;
series1.hover.stroke.size =.01;
Chart1.addSeries(series1);
Is it possible to just draw a rectangle using HTML 5 / Javascript Teecharts. I want to to draw rectangles like in gantt chart with specific x1,y1,x2 and y2 values.
I tried using the Format Object in Teecharts but it didn't help
Chart1.panel.format.rectPath(20,20,30,40);

To draw simple rectangle using html5...
window.onload = function() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.rect(188, 50, 200, 100);
context.fillStyle = '#8ED6FF';
context.fill();
context.lineWidth = 5;
context.strokeStyle = 'black';
context.stroke();
};
here is example link for gantt chart using html5
http://www.eecg.toronto.edu/~brousse1/Libraries/RGraph/docs/gantt.html

The next TeeChart Javascript v1.1 will incude the Gantt Series. Here it is the demo:
http://www.steema.us/files/jscript/demos/series/gantt/gantt.htm
We'll be glad to hear any comment about it.
Steema Support Central

Related

Draw butterfly graph on html canvas using javascript

I'm trying to draw a graph in a shape of a butterfly on html canvas using javascript. Parametric equations of the graph are:
x=(e^(cost) -2cos4t+sin^5( t/12))sint
y=(e^(cost) -2cos4t+sin^5( t/12))cost
t e [0, 20.5]
I have been trying but i can't figure it out. Thanks for your help :)
Here is a minimal example of a Lissajous curve for drawing a parametrized 2D curve on a javascript canvas. You should be able to adapt this for your curve
// get the handles and info on the HTML elements
var canvas = document.getElementById('Canvas');
var width = canvas.width;
var height = canvas.height;
var context = canvas.getContext('2d');
// construct a local coordinate system that is
// slightly larger than [-1,1]x[-1,1]
context.translate(width/2, height/2);
context.scale(width/2.1, height/2.1);
context.lineWidth = 0.02;
// construct and draw the curve
context.beginPath();
context.moveTo(0,0);
for(var x = 0; x < 6*Math.PI; x += 0.05)
context.lineTo(Math.sin(3*x),Math.sin(4*x));
context.stroke();
<canvas id="Canvas" width = "200" height = "200" />

draw outer and inner border around any canvas shape

How to draw outer and inner border around any canvas shape?
I'm drawing several stroke-only shapes on an html canvas, and I would like to draw an inner and outer border around them.
draft example:
Is there a generic why to do it for any shape (assuming it's a closed stroke-only shape)?
Two methods
There is no inbuilt way to do this and there are two programmatic ways that I use. The first is complicated and involves expanding and contracting the path then drawing along that path. This works for most situations but will fail in complex situation, and the solution has many variables and options to account for these complications and how to handle them.
The better of the two
The second and easiest way that I present below is by using the ctx.globalCompositeOperation setting to mask out what you want drawn or not. As the stroke is drawn along the center and the fill fills up to the center you can draw the stroke at twice the desired width and then either mask in or mask out the inner or outer part.
This does become problematic when you start to create very complex images as the masking (Global Composite Operation) will interfere with what has already been drawn.
To simplify the process you can create a second canvas the same size as the original as a scratch space. You can then draw the shape on he scratch canvas do the masking and then draw the scratch canvas onto the working one.
Though this method is not as fast as computing the expanded or shrunk path, it does not suffer from the ambiguities faced by moving points in the path. Nor does this method create the lines with the correct line join or mitering for the inside or outside edges, for that you must use a the other method. For most purposes the masking it is a good solution.
Below is a demo of the masking method to draw an inner or outer path. If you modify the mask by including drawing a stroke along with the fill you can also set an offset so that the outline or inline will be offset by a number of pixels. I have left that for you. (hint add stroke and set the line width to twice the offset distance when drawing the mask).
var demo = function(){
/** fullScreenCanvas.js begin **/
var canvas = ( function () {
canvas = document.getElementById("canv");
if(canvas !== null){
document.body.removeChild(canvas);
}
// creates a blank image with 2d context
canvas = document.createElement("canvas");
canvas.id = "canv";
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.position = "absolute";
canvas.style.top = "0px";
canvas.style.left = "0px";
canvas.style.zIndex = 1000;
canvas.ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
return canvas;
})();
var ctx = canvas.ctx;
/** fullScreenCanvas.js end **/
/** CreateImage.js begin **/
// creates a blank image with 2d context
var createImage = function(w,h){
var image = document.createElement("canvas");
image.width = w;
image.height =h;
image.ctx = image.getContext("2d");
return image;
}
/** CreateImage.js end **/
// define a shape for demo
var shape = [0.1,0.1,0.9,0.1,0.5,0.5,0.8,0.9,0.1,0.9];
// draws the shape as a stroke
var strokeShape = function (ctx) {
var w, h, i;
w = canvas.width;
h = canvas.height;
ctx.beginPath();
ctx.moveTo(shape[0] *w, shape[1] *h)
for (i = 2; i < shape.length; i += 2) {
ctx.lineTo(shape[i] * w, shape[i + 1] * h);
}
ctx.closePath();
ctx.stroke();
}
// draws the shape as filled
var fillShape = function (ctx) {
var w, h, i;
w = canvas.width;
h = canvas.height;
ctx.beginPath();
ctx.moveTo(shape[0] * w,shape[1] * h)
for (i = 2; i < shape.length; i += 2) {
ctx.lineTo(shape[i]*w,shape[i+1]*h);
}
ctx.closePath();
ctx.fill();
}
var drawInOutStroke = function(width,style,where){
// clear the workspace
workCtx.ctx.globalCompositeOperation ="source-over";
workCtx.ctx.clearRect(0, 0, workCtx.width, workCtx.height);
// set the width to double
workCtx.ctx.lineWidth = width*2;
workCtx.ctx.strokeStyle = style;
// fill colour does not matter here as its not seen
workCtx.ctx.fillStyle = "white";
// can use any join type
workCtx.ctx.lineJoin = "round";
// draw the shape outline at double width
strokeShape(workCtx.ctx);
// set comp to in.
// in means leave only pixel that are both in the source and destination
if (where.toLowerCase() === "in") {
workCtx.ctx.globalCompositeOperation ="destination-in";
} else {
// out means only pixels on the destination that are not part of the source
workCtx.ctx.globalCompositeOperation ="destination-out";
}
fillShape(workCtx.ctx);
ctx.drawImage(workCtx, 0, 0);
}
// clear in case of resize
ctx.globalCompositeOperation ="source-over";
ctx.clearRect(0,0,canvas.width,canvas.height);
// create the workspace canvas
var workCtx = createImage(canvas.width, canvas.height);
// draw the outer stroke
drawInOutStroke((canvas.width + canvas.height) / 45, "black", "out");
// draw the inner stroke
drawInOutStroke((canvas.width + canvas.height) / 45, "red", "in");
// draw the shape outline just to highlight the effect
ctx.strokeStyle = "white";
ctx.lineJoin = "round";
ctx.lineWidth = (canvas.width + canvas.height) / 140;
strokeShape(ctx);
};
// run the demo
demo();
// incase fullscreen redraw it all
window.addEventListener("resize",demo)

Rotating Globe Choropleth in D3

I'm trying to make a chorolpleth with a rotating globe in d3. I can get the globe to render out fine but I can't get the countries to fill with the proper color scale.
Longer explanation. I basically started with Mike Bostock's code for the spinning globe found here:
http://bl.ocks.org/mbostock/6747043
I've got some economic data for about 85 countries that I'm reading in from an external csv. And I'm trying to get the colors to map to the countries per the values in the csv. There's another Bostock example of a choropleth here (static and just the US and referenced frequently in SO d3 questions):
http://bl.ocks.org/mbostock/4060606
What I end up with are solid white (#fff) countries on the face of the globe. Which is not what I'm trying to get.
I added the ISO 3166-1 numeric codes to my csv so that I could match them to the same ids inside the topojson data. So my csv looks like:
country id curracct
Germany 276 260.9
Sweden 752 7.24
Etc.
My first thought was just to create a variable that was a function, which went through the length of the 'countries' from the topojson data and found the countries where the id equaled the id from the csv countries, then assigned the scaled color to them. Then I set 'context.fillStyle' equal to that variable/function. That didn't work.
Then I just put 'context.fillStyle' directly inside of a function (which is the code as it's currently written below). That didn't work either.
Again, I'm trying to get the 85 or so countries with data in the csv to appear color-coded on the front side spinning globe according to the scale I've set up.
My guess is that there is something I don't understand about the variable 'context' and what it's handling. If this were .style("fill", [put my function here to map the colors]) syntax I would be okay. So, anyone got any thoughts?
I'm not a coder. Actually I guess I am as I am trying to write some code. Maybe I should just say I'm a self-taught and mostly terrible coder. Although through examples, the JS console, and other questions on SO, I can usually work out where the errors are. This time I've reached a wall. Any help is appreciated. Thanks.
var width = 560,
height = 560,
speed = -1e-2,
start = Date.now();
var sphere = {type: "Sphere"};
var color = d3.scale.quantize()
.range(["#ffffd9", "#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"]);
var projection = d3.geo.orthographic()
.scale(width / 2.1)
.clipAngle(90)
.translate([width / 2, height / 2]);
var graticule = d3.geo.graticule();
var canvas = d3.select("body")
.append("canvas")
.attr("width", width)
.attr("height", height);
var context = canvas.node().getContext("2d");
var path = d3.geo.path()
.projection(projection)
.context(context);
queue()
.defer(d3.json, "/d3/world-110m.json")
.defer(d3.csv, "trade.csv")
.await(globeTrade);
function globeTrade(error, topo, data) {
var land = topojson.feature(topo, topo.objects.land),
countries = topojson.feature(topo, topo.objects.countries),
borders = topojson.mesh(topo, topo.objects.countries, function(a, b) { return a !== b; }),
grid = graticule();
color.domain([0, d3.max(data, function(d){return d.curracct})]);
d3.timer(function() {
var λ = speed * (Date.now() - start),
φ = -15;
context.clearRect(0, 10, width, height);
context.beginPath();
path(sphere);
context.lineWidth = 2.5;
context.strokeStyle = "#000";
context.stroke();
context.fillStyle = "#fff";
context.fill();
context.save();
context.translate(width / 2, 0);
context.scale(-1, 1);
context.translate(-width / 2, 0);
projection.rotate([λ + 180, -φ]);
context.beginPath();
path(land);
context.fillStyle = "#ddd" //changed to a nuetral gray
context.fill();
context.beginPath();
path(grid);
context.lineWidth = .5;
context.strokeStyle = "rgba(119,119,119,.5)";
context.stroke();
context.beginPath();
path(borders);
context.lineWidth = .25;
context.strokeStyle="#fff";
context.stroke();
context.restore();
projection.rotate([λ, φ]);
context.beginPath();
path(grid);
context.lineWidth = .5;
context.strokeStyle = "rgba(119,119,119,.5)";
context.stroke();
// This is where I am failing
context.beginPath();
path(countries);
function render (d){
for (var j = 0; j < countries.features.length; j++) {
if (d.id == countries.features[j].id) {
context.fillStyle = color(d.curracct)
}
else {
context.fillStyle = "#737368"; //left Bostock's color for now
}
}
}
context.fill();
context.lineWidth = .1;
context.strokeStyle = "#000";
context.stroke();
});
data.forEach(function(d, i) {
d.curracct = +d.curracct;
d.id = +d.id;
});
d3.select(self.frameElement).style("height", height + "px");
</script>
</body>

Changing shape's coords on keypress

I have a <canvas/>, and a shape rendering on it. I am trying to change the shape's coordinates on keypress, but am having no luck.
Here's my source:
var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
var radius = 35;
var xPos = 0;
context.beginPath();
context.arc(xPos, 0, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
$(document).keypress(function(event) {
if (event.which == 100) {
xPos++;
}
});
Another issue I am having is figuring out what keys are what number? Is there a chart somewhere? I saw two conflicting values on different sites.
The following article http://atomicrobotdesign.com/blog/htmlcss/move-objects-around-the-canvas-using-the-keyboard-and-jquery/ goes into great detail using jQuery to reference a Canvas object and then manipulate that object.
It also examines how to adjust the position of that Canvas object in response to keystrokes entered by the user.
Hope that helps.

How can i draw a Square in HTML5 Canvas at run time?

I am working on a HTML5 Project.There is a drawing graphics API to draw Rectangle (fillRectStrokeRect).But how can i draw a SQUARE. I have tried the following way to draw it
CODE
getMouse(e);
x2=mx; y2=my;
var width=endX-startX;
var height=endY-startY;
annCanvasContext.beginPath();
annCanvasContext.lineWidth=borderWidth;
var centerX=width/2;
var centerY=width/2;
var radius=width/2;
annCanvasContext.arc(centerX+5, centerY+5, radius, 0, 2 * Math.PI, false);
annCanvasContext.stroke();
Use fillRect or strokeRect with the width and height being equal.
var x = 0, y = 0,
side = 10;
ctx.fillRect(x, y, side, side);
Demo
As you say in the comments, if you want to fit the largest square in a circle, it's more Math related than about code. I'll trying explaining it to you, but you'll probably find better, more visual explanations elsewhere on the Internet.
Draw the diameter of the circle in a way that it divides your square into two equal parts. Now one part is a right angled triangle, which has two of its sides equal. We know the diameter. Using the Pythogorean theorem, you get this equation:
side^2 + side^2 = diameter^2.
Let's find the side now.
2(side^2) = diameter^2
side^2 = (diameter^2)/2
side = Math.sqrt( (diameter^2)/2 )
Now, to turn this into code.
var ctx = document.getElementById('canvas').getContext('2d'),
radius = 20;
ctx.canvas.addEventListener('click', function (e){
ctx.fillStyle = 'black';
ctx.arc(e.pageX, e.pageY, radius, 0, Math.PI*2, false);
ctx.fill();
ctx.beginPath();
ctx.fillStyle = 'red';
var diameter = radius * 2;
var side = Math.sqrt( (diameter * diameter)/2 );
ctx.fillRect(e.pageX - side/2, e.pageY - side/2, side, side);
ctx.closePath();
}, false);
This would draw a square inside a circle wherever you click on the canvas.
Demo

Categories

Resources