Adding grid over Fabric.js canvas - javascript

I just started using Fabric.js (I have to say, I'm impressed).
I want to add a grid over the fabric objects. In the following code, I am putting my grid canvas right over on the Fabric canvas. The problem here is that, I now cannot move my fabric objects!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<script type='text/javascript' src='http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.2.0/fabric.all.min.js'></script>
</head>
<body>
<div style="height:480px;width:640px;border:1px solid #ccc;position:relative;font:16px/26px Georgia, Garamond, Serif;overflow:auto;">
<canvas id="rubber" width="800" height="800"
style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="myCanvas" width="800" height="800"
style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>
<script>
//<![CDATA[
$(window).load(function(){
$(document).ready(function () {
function renderGrid(x_size,y_size, color)
{
var canvas = $("#myCanvas").get(0);
var context = canvas.getContext("2d");
context.save();
context.lineWidth = 0.5;
context.strokeStyle = color;
// horizontal grid lines
for(var i = 0; i <= canvas.height; i = i + x_size)
{
context.beginPath();
context.moveTo(0, i);
context.lineTo(canvas.width, i);
context.closePath();
context.stroke();
}
// vertical grid lines
for(var j = 0; j <= canvas.width; j = j + y_size)
{
context.beginPath();
context.moveTo(j, 0);
context.lineTo(j, canvas.height);
context.closePath();
context.stroke();
}
context.restore();
}
renderGrid(10,15, "gray");
});
});//]]>
var canvas = new fabric.Canvas('rubber');
canvas.add(new fabric.Circle({ radius: 30, fill: '#f55', top: 100, left: 100 }));
canvas.selectionColor = 'rgba(0,255,0,0.3)';
canvas.selectionBorderColor = 'red';
canvas.selectionLineWidth = 5;
</script>
</body>
</html>
I am hoping that there is a way to do this in Fabric itself.
Any help would be awesome, thanks!

This two lines of code will work:
var gridsize = 5;
for(var x=1;x<(canvas.width/gridsize);x++)
{
canvas.add(new fabric.Line([100*x, 0, 100*x, 600],{ stroke: "#000000", strokeWidth: 1, selectable:false, strokeDashArray: [5, 5]}));
canvas.add(new fabric.Line([0, 100*x, 600, 100*x],{ stroke: "#000000", strokeWidth: 1, selectable:false, strokeDashArray: [5, 5]}));
}

A shorter version and more generic for copy/paste :
var oCanvas; // must be your canvas object
var gridWidth; // <= you must define this with final grid width
var gridHeight; // <= you must define this with final grid height
// to manipulate grid after creation
var oGridGroup = new fabric.Group([], {left: 0, top: 0});
var gridSize = 20; // define grid size
// define presentation option of grid
var lineOption = {stroke: 'rgba(0,0,0,.4)', strokeWidth: 1, selectable:false, strokeDashArray: [3, 3]};
// do in two steps to limit the calculations
// first loop for vertical line
for(var i = Math.ceil(gridWidth/gridSize); i--;){
oGridGroup.add( new fabric.Line([gridSize*i, 0, gridSize*i, gridHeight], lineOption) );
}
// second loop for horizontal line
for(var i = Math.ceil(gridHeight/gridSize); i--;){
oGridGroup.add( new fabric.Line([0, gridSize*i, gridWidth, gridSize*i], lineOption) );
}
// Group add to canvas
oCanvas.add(oGridGroup);

I hope this will help you----
function draw_grid(grid_size) {
grid_size || (grid_size = 25);
currentCanvasWidth = canvas.getWidth();
currentcanvasHeight = canvas.getHeight();
// Drawing vertical lines
var x;
for (x = 0; x <= currentCanvasWidth; x += grid_size) {
this.grid_context.moveTo(x + 0.5, 0);
this.grid_context.lineTo(x + 0.5, currentCanvasHeight);
}
// Drawing horizontal lines
var y;
for (y = 0; y <= currentCanvasHeight; y += grid_size) {
this.grid_context.moveTo(0, y + 0.5);
this.grid_context.lineTo(currentCanvasWidth, y + 0.5);
}
grid_size = grid_size;
this.grid_context.strokeStyle = "black";
this.grid_context.stroke();
}

My solution is -
var width = canvas.width;
var height = canvas.height;
var j = 0;
var line = null;
var rect = [];
var size = 20;
console.log(width + ":" + height);
for (var i = 0; i < Math.ceil(width / 20); ++i) {
rect[0] = i * size;
rect[1] = 0;
rect[2] = i * size;
rect[3] = height;
line = null;
line = new fabric.Line(rect, {
stroke: '#999',
opacity: 0.5,
});
line.selectable = false;
canvas.add(line);
line.sendToBack();
}
for (i = 0; i < Math.ceil(height / 20); ++i) {
rect[0] = 0;
rect[1] = i * size;
rect[2] = width;
rect[3] = i * size;
line = null;
line = new fabric.Line(rect, {
stroke: '#999',
opacity: 0.5,
});
line.selectable = false;
canvas.add(line);
line.sendToBack();
}
canvas.renderAll();
You have to save all line objects for removing grid, or you can added all line objects to a group, and you can remove the group for removing grid, well I think this is not elegant one, but worked.

If you don't insist on generating your grid dynamically you might want to consider the native overlay image function that fabric.js provides.
var canvas = new fabric.Canvas('rubber');
canvas.setOverlayImage('grid.png', canvas.renderAll.bind(canvas));
It won't hinder interactions with the objects on the canvas at all.

I really liked #Draeli's answer, but it seemed it wasn't working with the latest fabric version. Fixed the old one and added one slight adjustment that was necessary for myself - centring the grid.
Anyhow, maybe someone else finds it useful:
const gridSize = 100;
const width = this.canvas.getWidth();
const height = this.canvas.getHeight();
const left = (width % gridSize) / 2;
const top = (height % gridSize) / 2;
const lines = [];
const lineOption = {stroke: 'rgba(0,0,0,1)', strokeWidth: 1, selectable: false};
for (let i = Math.ceil(width / gridSize); i--;) {
lines.push(new fabric.Line([gridSize * i, -top, gridSize * i, height], lineOption));
}
for (let i = Math.ceil(height / gridSize); i--;) {
lines.push(new fabric.Line([-left, gridSize * i, width, gridSize * i], lineOption));
}
const oGridGroup = new fabric.Group(lines, {left: 0, top: 0});
this.canvas.add(oGridGroup);
this.canvas - this supposedly is the fabric instance.

Here is my solution, works with Fabric Js 4.
at the end there is 2 events listeners that append the grid when object moving and remove the grid when object move end. (improvement of #draeli answer https://stackoverflow.com/a/35936606/1727357 )
(function () {
const gcd = (a, b) => {
if (!b) {
return a;
}
return gcd(b, a % b);
}
const gridWidth = canvas.getWidth();
const gridHeight = canvas.getHeight();
const oGridGroup = [];
console.log(gcd(gridWidth, gridHeight));
const gridRows = gcd(gridWidth, gridHeight);
const gridCols = gcd(gridWidth, gridHeight);
const lineOption = { stroke: 'rgba(0,0,0,.1)', strokeWidth: 1, selectable: false, evented: false };
for (let i = 0; i <= gridWidth; i += gridCols) {
oGridGroup.push(new fabric.Line([i, 0, i, gridHeight], lineOption));
}
for (let i = 0; i <= gridHeight; i += gridRows) {
oGridGroup.push(new fabric.Line([0, i, gridWidth, i], lineOption));
}
const theGorup = new fabric.Group(oGridGroup);
theGorup.set({
selectable: false,
evented: false
})
canvas.on('mouse:down', function (event) {
if (event.target) {
canvas.add(theGorup);
}
});
canvas.on('mouse:up', function (event) {
canvas.remove(theGorup);
});
}())

Updated:
Answer is based on the code posted by rafi:
I have updated the missing grid_context.
Kindly replace "<your canvas Id>" with your canvas Id in string. For e.g. "myCanvas".
Usually, any operation you do on the canvas will clear out grid on the canvas, register the after:render event on fabric.js canvas to redraw it. So you can always see it.
var canvas = new fabric.Canvas(<your canvas Id>);
canvas.on('after:render',function(ctx){
draw_grid(25);
});
function draw_grid(grid_size) {
grid_size || (grid_size = 25);
var currentCanvas = document.getElementById(<your canvas Id>);
var grid_context = currentCanvas.getContext("2d");
var currentCanvasWidth = canvas.getWidth();
var currentCanvasHeight = canvas.getHeight();
// Drawing vertical lines
var x;
for (x = 0; x <= currentCanvasWidth; x += grid_size) {
grid_context.moveTo(x + 0.5, 0);
grid_context.lineTo(x + 0.5, currentCanvasHeight);
}
// Drawing horizontal lines
var y;
for (y = 0; y <= currentCanvasHeight; y += grid_size) {
grid_context.moveTo(0, y + 0.5);
grid_context.lineTo(currentCanvasWidth, y + 0.5);
}
grid_context.strokeStyle = "#0000002b";
grid_context.stroke();
}

Related

Pointing arrow on precise location on donut chart

I am trying to point to certain parts on a donut chart. The chart is divided into 9 parts.
comArray is the main array which contain all parts. angleArray is the angles in degrees for each part. useArray contains the parts that should be located through the pointer.
My code is working for sometime but then it starts locating on some different point. For example, if pointer needs to point to 3 it locates properly but after 1 hour it will start locating on the 6 part for 3 part.
What I am doing wrong? You can check the working example here: https://bishttech.com/newtest/
$(document).ready(function() {
var comArray = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // main array of all parts
var angleArray = [20, 60, 100, 140, 180, 220, 260, 300, 340]; // angle in degrees for all parts
var useArray = [3, 6, 8, 2]; // pointer should stop on these parts
//console.log(areacount);
var canvas = document.getElementById("chart");
var ctx = canvas.getContext("2d");
function drawMultiRadiantCircle(xc, yc, r, radientColors) {
var partLength = (2 * Math.PI) / radientColors.length;
var start = 0;
var gradient = null;
var startColor = null,
endColor = null;
var startAngle = 0;
for (var i = 0; i < radientColors.length; i++) {
startColor = radientColors[i];
// endColor = radientColors[(i + 1) % radientColors.length];
endColor = adjust(startColor, -30);
// x start / end of the next arc to draw
var xStart = xc + Math.cos(start) * r;
var xEnd = xc + Math.cos(start + partLength) * r;
// y start / end of the next arc to draw
var yStart = yc + Math.sin(start) * r;
var yEnd = yc + Math.sin(start + partLength) * r;
ctx.beginPath();
gradient = ctx.createLinearGradient(xStart, yStart, xEnd, yEnd);
gradient.addColorStop(0, endColor);
gradient.addColorStop(0.5, startColor);
gradient.addColorStop(1.0, endColor);
ctx.strokeStyle = gradient;
ctx.arc(xc, yc, r, start, start + partLength);
ctx.lineWidth = 30;
ctx.stroke();
ctx.closePath();
start += partLength;
startAngle = partLength;
}
}
var someColors = ["#fb4168", "#4efb7f", "#fbf672", "#63e0fb", "#5b5bfb", "#f079fb", "#e0dffb", "#1aa3fb", "#1aa3fb"];
drawMultiRadiantCircle(300, 300, 200, someColors);
// get location of value
function getCurLoc(value) {
for (var i = 0; i < comArray.length; i++) {
if (value == comArray[i]) {
return i;
break;
}
}
}
var startingPnt = 0;
var curangleDegrees = 0;
var prevangleDegrees = 0;
var prevLoc = 0;
var curLoc = 0;
var rotateNum = 0;
var diffLoc = 0;
//function for displaying data on chart
function displayData() {
var maxPnt = useArray.length - 1;
var currentValue = useArray[startingPnt];
var getLoc = getCurLoc(currentValue); // getting location of value in comArray
if (rotateNum == 0) {
curangleDegrees = angleArray[getLoc];
curLoc = getLoc;
} else {
curLoc = getLoc;
diffLoc = curLoc - prevLoc;
curangleDegrees = (diffLoc * 40);
}
$(".img").rotate(curangleDegrees, {
easing: 'easeInExpo'
});
console.log(getLoc);
if (startingPnt == maxPnt) {
startingPnt = 0;
} else {
startingPnt++;
}
prevLoc = curLoc;
prevangleDegrees = curangleDegrees;
rotateNum++;
}
setInterval(function() {
displayData();
}, 10000);
function adjust(color, amount) {
return '#' + color.replace(/^#/, '').replace(/../g, color => ('0' + Math.min(255, Math.max(0, parseInt(color, 16) + amount)).toString(16)).substr(-2));
}
});
.img {
margin: 48px 52px;
position: absolute;
z-index: 1;
}
#container {
width: 50%;
display: block;
margin: 0 auto;
position: relative;
}
#chart {
position: relative;
z-index: 20;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="container">
<img class='img' src="images/arrowcircle.png" alt="" />
<canvas id="chart" width="800" height="800"></canvas>
</div>

FabricJS: big grid objects is blurry

I want to draw a large grid with fabricjs, but it is too blurry. I use fabricJS canvas.toSVG() export to a svg file, and I open the svg file in browser, it's view good. so I think this is most possible likely a bug for edge.
The test code is:
var data = [];
var temp = [0,0,-0.012,-0.012,-0.012,-0.012,-0.012,-0.012,0,0,-0.012,-0.012,0,0.049,0.073,0.049,0.049,0.037,-0.012,-0.012,-0.024,-0.049,-0.024,-0.049,-0.061,-0.012,-0.061,-0.086,0.061,0.146,0.354,0.403,-0.647,-1.88,-1.672,-0.757,-0.33,-0.098,0.024,0.012,0.073,0.122,0.098,0.146,0.183,0.171,0.207,0.232];
for (var i = 0; i < 200; i++) {
data = data.concat(temp);
}
// case 1 : blurry
var canvas1 = new fabric.Canvas("ecg1");
var width = 8000;
var height = 400;
canvas1.setWidth(width);
canvas1.setHeight(height);
var bg1 = getBackgroundPath(width, height);
var ecg1 = getEcgPath(data);
canvas1.add(bg1);
canvas1.add(ecg1);
canvas1.renderAll(); // blurry
// case 2 : ok
var canvas2 = new fabric.Canvas("ecg2");
var data2 = data.slice(0, 3000);
width = 1000;
height = 400;
canvas2.setWidth(width);
canvas2.setHeight(height);
var bg2 = getBackgroundPath(width, height);
var ecg2 = getEcgPath(data2);
canvas2.add(bg2);
canvas2.add(ecg2);
canvas2.renderAll();
// case 3 : blurry
var canvas3 = new fabric.Canvas("ecg3");
canvas3.setWidth(width);
canvas3.setHeight(height);
canvas3.add(new fabric.Group([bg2, ecg2]));
canvas3.renderAll();
function getBackgroundPath(width, height) {
var grid = [];
for (var y = 0; y <= height; y += 10) {
grid.push("M");
grid.push("0");
grid.push(y);
grid.push("H");
grid.push(width);
}
for (var x = 0; x <= width; x += 10) {
grid.push("M");
grid.push(x);
grid.push("0");
grid.push("V");
grid.push(height);
}
return new fabric.Path(grid.join(" "), {
top : 0,
left : 0,
stroke: 'pink',
strokeWidth: 1
});
}
function getEcgPath(data) {
var xm = 2;
var ym = 100;
var max = Math.max.apply(Math, data);
var path = [];
for (var i = 0; i < data.length; i++) {
path.push("L");
path.push(i * xm);
path.push((max - data[i]) * ym);
}
path[0] = "M";
return new fabric.Path(path.join(" "), {
top : 0,
left : 0,
fill : '',
stroke: 'black',
strokeWidth: 1
});
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<canvas id="ecg1"></canvas>
<canvas id="ecg2"></canvas>
<canvas id="ecg3"></canvas>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.3/fabric.min.js" ></script>
</body>
</html>
the result is
Please have further reading here:
http://fabricjs.com/fabric-object-caching
This question is actually easily solvable disabling caching for the ECG line.
If your application needs to draw just a big path or an handfull of them, caching is not necessary.
How caching works?
Caching draw the object on a separate canvas and then reuse that canvas every frame when you move it.
This is way more performing than having to execute multiple fill and stroke operation each frame for many objects, especially when objects are complex.
To avoid performances pitfall the canvas used for caching is limited to 2 mega pixels by default ( you can push it up changing fabric.perfLimitSizeTotal ) and whatever is the mega pixel size, the largest size is limited to 4096 by default ( if you do not need to support ie11 you can make it bigger changing fabric.maxCacheSideLimit ).
In your case the path is smoothly handled by the cpu.
For the grid we need some more code.
var data = [];
var temp = [0,0,-0.012,-0.012,-0.012,-0.012,-0.012,-0.012,0,0,-0.012,-0.012,0,0.049,0.073,0.049,0.049,0.037,-0.012,-0.012,-0.024,-0.049,-0.024,-0.049,-0.061,-0.012,-0.061,-0.086,0.061,0.146,0.354,0.403,-0.647,-1.88,-1.672,-0.757,-0.33,-0.098,0.024,0.012,0.073,0.122,0.098,0.146,0.183,0.171,0.207,0.232];
for (var i = 0; i < 200; i++) {
data = data.concat(temp);
}
// case 1 : blurry
var canvas1 = new fabric.Canvas("ecg1");
var width = 8000;
var height = 400;
canvas1.setWidth(width);
canvas1.setHeight(height);
var bg1 = getBackgroundPath(width, height);
var ecg1 = getEcgPath(data);
canvas1.add(bg1);
canvas1.add(ecg1);
canvas1.renderAll(); // blurry
function getBackgroundPath(width, height) {
var grid = [];
for (var y = 0; y <= height; y += 10) {
grid.push("M");
grid.push("0");
grid.push(y);
grid.push("H");
grid.push(width);
}
for (var x = 0; x <= width; x += 10) {
grid.push("M");
grid.push(x);
grid.push("0");
grid.push("V");
grid.push(height);
}
return new fabric.Path(grid.join(" "), {
top : 0,
left : 0,
stroke: 'pink',
strokeWidth: 1
});
}
function getEcgPath(data) {
var xm = 2;
var ym = 100;
var max = Math.max.apply(Math, data);
var path = [];
for (var i = 0; i < data.length; i++) {
path.push("L");
path.push(i * xm);
path.push((max - data[i]) * ym);
}
path[0] = "M";
return new fabric.Path(path.join(" "), {
top : 0,
left : 0,
fill : '',
stroke: 'black',
strokeWidth: 1,
objectCaching: false,
});
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<canvas id="ecg1"></canvas>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.3/fabric.min.js" ></script>
</body>
</html>
#AndreaBogazzi
Thanks your answer. After I use fabric.Object.prototype.objectCaching = false, it's shows good.
In my application, the draw grid code is as follows.
var data = [];
var temp = [0,0,-0.012,-0.012,-0.012,-0.012,-0.012,-0.012,0,0,-0.012,-0.012,0,0.049,0.073,0.049,0.049,0.037,-0.012,-0.012,-0.024,-0.049,-0.024,-0.049,-0.061,-0.012,-0.061,-0.086,0.061,0.146,0.354,0.403,-0.647,-1.88,-1.672,-0.757,-0.33,-0.098,0.024,0.012,0.073,0.122,0.098,0.146,0.183,0.171,0.207,0.232];
for (var i = 0; i < 200; i++) {
data = data.concat(temp);
}
// case 1 : blurry
var canvas1 = new fabric.Canvas("ecg1");
var width = 8000;
var height = 400;
canvas1.setWidth(width);
canvas1.setHeight(height);
var bg11 = getBackgroundDot(width, height);
var bg12 = getBackgroundPath(width, height);
var ecg1 = getEcgPath(data);
canvas1.add(bg11);
canvas1.add(bg12);
canvas1.add(ecg1);
canvas1.renderAll(); // blurry
function getBackgroundDot() {
var dotLineWidth = 2;
var dot = [];
dot.push("M 0 0");
for (var y = 0; y <= height; y += 10) {
if (y % 50 == 0) {
continue;
}
dot.push("M");
dot.push("0");
dot.push(y);
dot.push("H");
dot.push(width);
}
var sda = [0, 10];
for (var i = 1; i < 5; i++) {
sda.push(dotLineWidth);
sda.push(8);
}
return new fabric.Path(dot.join(" "), {
top : 0,
left : 0,
stroke: 'pink',
strokeWidth: dotLineWidth,
strokeDashArray: sda
});
}
function getBackgroundPath(width, height) {
var grid = [];
for (var y = 0; y <= height; y += 50) {
grid.push("M");
grid.push("0");
grid.push(y);
grid.push("H");
grid.push(width);
}
for (var x = 0; x <= width; x += 50) {
grid.push("M");
grid.push(x);
grid.push("0");
grid.push("V");
grid.push(height);
}
return new fabric.Path(grid.join(" "), {
top : 0,
left : 0,
stroke: 'pink',
strokeWidth: 1
});
}
function getEcgPath(data) {
var xm = 2;
var ym = 100;
var max = Math.max.apply(Math, data);
var path = [];
for (var i = 0; i < data.length; i++) {
path.push("L");
path.push(i * xm);
path.push((max - data[i]) * ym);
}
path[0] = "M";
return new fabric.Path(path.join(" "), {
top : 0,
left : 0,
fill : '',
stroke: 'black',
strokeWidth: 1
});
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<canvas id="ecg1"></canvas>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.3/fabric.min.js" ></script>
</body>
</html>

Creating a checkered board with pieces in HTML5 canvas

I am experimenting with canvas in HTML and JS and attempting to draw a canvas of a chess board with 16 pieces on each side of it. I was able to create the chess board but am stuck on how I would draw just specifically the 16 pieces on each side (The pieces can just be circles so just one side with 16 red circles, one side with 16 blue circles).
I don't know why this is so confusing to me, I know you probably just need a for loop stopping at the specific coordinates but to get different colored pieces on each side as well as stopping at certain part is giving me trouble.
I would just like assistance on where in my code would I be placing the chess pieces in. If you could just modify my current code and place comments on where you made the changes so I could see then that would be very appreciated.
Here is what I have so far to make the checkers board:
<canvas id="canvas" width="300" height="300"></canvas>
function drawCheckeredBackground(can, nRow, nCol) {
var ctx = can.getContext("2d");
var w = can.width;
var h = can.height;
nRow = nRow || 8;
nCol = nCol || 8;
w /= nCol;
h /= nRow;
for (var i = 0; i < nRow; ++i) {
for (var j = 0, col = nCol / 2; j < col; ++j) {
ctx.rect(2 * j * w + (i % 2 ? 0 : w), i * h, w, h);
}
}
ctx.fill();
}
var canvas = document.getElementById("canvas");
drawCheckeredBackground(canvas);
Here is how I want the chess board to look like, with 16 pieces on each side like so. I just quickly made this example in paint:
https://i.imgur.com/BvbxzSZ.png
This isn't the most beautiful solution possible, but it should offer some basic ideas and is adjustable using your step variable idea. Chances are, you'll need to refactor when going for actual pieces.
const drawBoard = (ctx, step) => {
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
ctx.fillStyle = (i + j) & 1 ? "black" : "white";
ctx.fillRect(j * step, i * step, step, step);
}
}
};
const drawPieces = (ctx, y, color, step) => {
ctx.fillStyle = color;
for (let i = y; i < 2 * step + y; i += step) {
for (let j = step / 2; j < 8 * step; j += step) {
ctx.beginPath();
ctx.arc(j, i - step / 2, step / 3, 0, Math.PI * 2);
ctx.fill();
}
}
};
const step = 60;
const c = document.createElement("canvas");
c.height = c.width = step * 8;
document.body.appendChild(c);
const ctx = c.getContext("2d");
drawBoard(ctx, step);
drawPieces(ctx, step, "red", step);
drawPieces(ctx, step * 7, "blue", step);
Play with it at JSFiddle.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
display: block;
margin: auto;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
// Self executing function
void function() {
// Turn on strict js rules for this scope
"use strict";
// Classes
function ChessPeice(x,y,radius) {
this.x = x || 0.0;
this.y = y || 0.0;
this.radius = radius || 1.0;
}
ChessPeice.prototype = {
tick: function() {
},
render: function(ctx) {
ctx.moveTo(
this.x + this.radius,
this.y
);
ctx.arc(
this.x,
this.y,
this.radius,
0.0,
2.0 * Math.PI,
false
);
}
};
// Constructor, when called with 'new' creates an object and puts it
// in the 'this' variable, new properties can then be added to it.
function Chessboard(width,height) {
this.boardWidth = width || 1;
this.boardHeight = height || 1;
this.tileWidth = this.boardWidth / this.H_TILE_COUNT;
this.tileHeight = this.boardHeight / this.V_TILE_COUNT;
this.whitePeices = [];
this.blackPeices = [];
for (var y = 0; y < 2; ++y) {
for (var x = 0; x < this.V_TILE_COUNT; ++x) {
this.whitePeices.push(
new ChessPeice(
x * this.tileWidth + (this.tileWidth >> 1),
y * this.tileHeight + (this.tileHeight >> 1),
this.CHESS_PIECE_RADIUS
)
);
this.blackPeices.push(
new ChessPeice(
x * this.tileWidth + (this.tileWidth >> 1),
(this.V_TILE_COUNT - 1 - y) * this.tileHeight + (this.tileHeight >> 1),
this.CHESS_PIECE_RADIUS
)
);
}
}
}
// Prototype object, all objects created with 'new Chessboard()'
// will share the properties in the prototype, use it for constant values
// & class functions
Chessboard.prototype = {
H_TILE_COUNT: 8, // How many white & black tiles per axis?
V_TILE_COUNT: 8,
EDGE_THICKNESS: 10.0,
EDGE_COLOUR: "#603E11FF",
WHITE_TILE_COLOUR: "#BBBBBBFF",
BLACK_TILE_COLOUR: "#555555FF",
CHESS_PIECE_RADIUS: 5.0,
WHITE_PIECE_COLOUR: "#EEEEEEFF",
BLACK_PIECE_COLOUR: "#333333FF",
tick: function() {
// You can add game logic here
},
render: function(ctx) {
// Draw white tiles
var x = 0;
var y = 0;
var totalTiles = this.H_TILE_COUNT * this.V_TILE_COUNT;
ctx.fillStyle = this.WHITE_TILE_COLOUR;
ctx.beginPath();
for (var i = 0; i < totalTiles; ++i) {
ctx.rect(
x * this.tileWidth,
y * this.tileHeight,
this.tileWidth,
this.tileHeight
);
x += 2;
if (x >= this.H_TILE_COUNT) {
x = this.H_TILE_COUNT - x + 1;
++y;
}
}
ctx.fill();
// Draw black tiles
x = 1;
y = 0;
ctx.fillStyle = this.BLACK_TILE_COLOUR;
ctx.beginPath();
for (var i = 0; i < totalTiles; ++i) {
ctx.rect(
x * this.tileWidth,
y * this.tileHeight,
this.tileWidth,
this.tileHeight
);
x += 2;
if (x >= this.H_TILE_COUNT) {
x = this.H_TILE_COUNT - x + 1;
++y;
}
}
ctx.fill();
// Draw edge
ctx.lineWidth = this.EDGE_THICKNESS >> 1;
ctx.strokeStyle = this.EDGE_COLOUR;
ctx.beginPath();
ctx.rect(0,0,this.boardWidth,this.boardHeight);
ctx.stroke();
// Draw white pieces
ctx.lineWidth = 2;
ctx.strokeStyle = "#000000FF";
ctx.fillStyle = this.WHITE_PIECE_COLOUR;
ctx.beginPath();
for (var i = 0; i < this.whitePeices.length; ++i) {
this.whitePeices[i].render(ctx);
}
ctx.fill();
ctx.stroke();
// Draw black pieces
ctx.lineWidth = 2;
ctx.strokeStyle = "#000000FF";
ctx.fillStyle = this.BLACK_PIECE_COLOUR;
ctx.beginPath();
for (var i = 0; i < this.blackPeices.length; ++i) {
this.blackPeices[i].render(ctx);
}
ctx.fill();
ctx.stroke();
}
};
// Variables
var canvasWidth = 160;
var canvasHeight = 160;
var canvas = null;
var ctx = null;
var board = null;
// Game Loop
function loop() {
// Tick (Update game logic)
board.tick();
// Render
ctx.fillStyle = "gray";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
board.render(ctx);
//
requestAnimationFrame(loop);
}
// Entry Point (Runs when the page loads)
onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx = canvas.getContext("2d");
board = new Chessboard(canvasWidth,canvasHeight);
loop();
}
}();
</script>
</body>
</html>

Stopping animated rain in Canvas smmoothly

Rain Picture HereSo my issue isn't stopping the rain its stopping the making of the rain so the already rendered rain completes its animation off the screen.
I tried setInterval and setTimeout in JS but it just freezes.
And using JQuery to remove canvas tag takes off all drops at once.
Any ideas or direction would be great!
var canvas = document.getElementById("rainCanvas");
var ctx = canvas.getContext("2d");
var canvasW = window.innerWidth;
var canvasH = window.innerHeight;
canvas.height = canvasH;
canvas.width = canvasW;
var mf = 70;
var drops = [];
for(var i = 0; i < mf; i++){
drops.push({
x: Math.random()*canvasW,
y: Math.random()*canvasH,
r: Math.random()*5+2,
d: Math.random() + 1
})
}
function fill() {
ctx.fill();
}
function drawRain(){
ctx.clearRect(0, 0, canvasW, canvasH);
ctx.fillStyle = "rgba(255, 255, 255, .5)";
ctx.beginPath();
for(var i = 0; i < mf; i++){
var f = drops[i];
ctx.moveTo(f.x-5, f.y);
ctx.lineTo(f.x, f.y-15);
ctx.lineTo(f.x+5, f.y);
ctx.arc(f.x, f.y + f.r*.7,5, 0, Math.PI, false);
}
fill();
moveRain();
}
function moveRain(){
for(var i = 0; i < mf; i++){
var f = drops[i];
f.y += Math.pow(f.d, 2) + 1;
if(f.y > canvasH){
drops[i] = {x: Math.random()*canvasW, y: 0, r: f.r, d: f.d};
}
}
}
var i = setInterval(drawRain, 20);
setTimeout(function( ) { clearInterval(); }, 2000);
canvas{ background-color: black }
<canvas id="rainCanvas"></canvas>
What you want to do is set a flag to stop the rain from wrapping back to the top in your function to stop raining:
var stopRain = false;
...
setTimeout(function( ) { stopRain = true; }, 2000);
Now inside moveRain when that variable is true instead of moving it back to the top remove it from the array. Once we removed all the drops we can then clear the interval as it's no longer needed:
function moveRain(){
for(var i = 0; i < mf; i++){
var f = drops[i];
f.y += Math.pow(f.d, 2) + 1;
if(f.y > canvasH){
if(stopRain) { // When we stop raining
drops.splice(i, 1); // Remove drop from array
mf--; // Make sure to update the "length"
if(mf<1) clearInterval(i); // If there are not more drops clear the interval
} else drops[i] = {x: Math.random()*canvasW, y: 0, r: f.r, d: f.d};
}
}
}
Fiddle Example
You could also use drops.length instead of using mf, this way you don't need to do mf--.
Here I fixed some of the code and added a rainDensity variable which controls the count of new raindrops. The original code was designed to have a fixed amount of raindrops, it had to be changed to achieve the desired effect.
window.onload = function(){
var canvas = document.getElementById("rainCanvas");
var ctx = canvas.getContext("2d");
var canvasW = window.innerWidth;
var canvasH = window.innerHeight;
canvas.height = canvasH;
canvas.width = canvasW;
var drops = [];
function makeDrop() {
drops.push({
x: Math.random()*canvasW,
y: -10,
r: Math.random()*4+1,
d: Math.pow(Math.random() + 1, 2) + 1
})
}
function drawRain(){
ctx.clearRect(0, 0, canvasW, canvasH);
ctx.fillStyle = "rgba(128, 128, 255, .5)";
for(var f of drops){
ctx.beginPath();
ctx.moveTo(f.x-5, f.y);
ctx.lineTo(f.x, f.y-15);
ctx.lineTo(f.x+5, f.y);
ctx.arc(f.x, f.y + f.r*.7,5, 0, Math.PI, false);
ctx.fill();
}
}
function handleFrame() {
drawRain();
updateRain();
}
function updateRain() {
moveRain();
makeNewDrops();
}
var dropPerFrameCounter = 0;
var startTime = Date.now();
function makeNewDrops() {
var elapsedTime = (Date.now() - startTime) / 1000;
// rainDensity: set it to 0 to stop rain
var rainDensity = Math.max(0, Math.sin(elapsedTime / 3) + 0.5);
dropPerFrameCounter += rainDensity;
while (dropPerFrameCounter >= 1) {
dropPerFrameCounter--;
makeDrop();
}
}
function moveRain() {
for(var f of drops){
f.y += f.d;
}
drops = drops.filter(d => d.y < canvasH);
}
var intervalRender = setInterval(handleFrame, 20);
}
<canvas id="rainCanvas"></canvas>
Had to add an answer because the example all used setInterval to do the animation which looks awful. Use requestAnimationFrame to animate. Also fixed some other problems with the code.
I have added a pause the pauses the animation when you click on the canvas. Clicking again will continue.
var canvas = document.getElementById("rainCanvas");
var ctx = canvas.getContext("2d");
var canvasW = window.innerWidth;
var canvasH = window.innerHeight;
canvas.height = canvasH;
canvas.width = canvasW;
var mf = 70;
var drops = [];
var paused = false;
for(var i = 0; i < mf; i++){
drops.push({
x: Math.random()*canvasW,
y: Math.random()*canvasH,
r: Math.random()*5+2,
d: Math.random() + 1
})
}
function drawRain(){
if(!paused){
ctx.clearRect(0, 0, canvasW, canvasH);
ctx.fillStyle = "rgba(255, 255, 255, .5)";
ctx.beginPath();
for(var i = 0; i < mf; i++){
var f = drops[i];
ctx.moveTo(f.x - 2.5 * f.d, f.y);
ctx.lineTo(f.x, f.y - 7.5 * f.d);
ctx.lineTo(f.x + 2.5 * f.d, f.y);
ctx.arc(f.x, f.y + f.r * 0.7, 2.5 * f.d, 0, Math.PI, false);
}
ctx.fill();
for(var i = 0; i < mf; i++){
var f = drops[i];
f.y += Math.pow(f.d, 2) + 1;
if(f.y > canvasH + 15){ // make sure completely off the bottom
// dont create a new drop reuse it will stop GC from
// having to interrupt the code.
f.x = Math.random()*canvasW;
f.y = -6; // move off top
}
}
}
requestAnimationFrame(drawRain);
}
requestAnimationFrame(drawRain);
canvas.addEventListener("click",()=>{paused = ! paused});
canvas{
background-color: black;
position : absolute;
top : 0px;
left : 0px;
}
<canvas id="rainCanvas"></canvas>

Integrate GSAP with canvas to make a curvy timeline

I'm currently working on a canvas timeline-like animation.
This is what I made so far...
$(function() {
'use strict';
var canvas = document.querySelector('#canvas');
var ctx = canvas.getContext('2d');
var s = 20;
var arr = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100];
var colorP = ['#ff5454', '#ffa144', '#ffe256', '#aaff75', '#8cd8ff', '#b5b6ff', '#b882ff'];
var dots = [];
var rDots = [];
function init() {
var reverse = true;
for (var i = 0; i < 100; i++) {
var dot = new Object();
var height = null;
if (arr.indexOf(i) != -1) {
dot.x = s;
dot.y = 50;
dot.r = 3;
dot.c = 'red';
dot.f = 'rgba(0,0,0,0)';
dot.t = '1';
dot.s = 0;
rDots.push(dot);
} else {
dot.x = s;
dot.y = 50;
dot.r = 1;
dot.c = 'red';
dot.f = '';
dot.t = '';
dot.s = 0;
}
s += 10;
dots.push(dot);
};
function tween() {
height = Math.floor(Math.random() * (75 - 25) + 25);
TweenMax.staggerTo(dots, 5, {
y: height,
yoyo: true,
repeat: 'repeat',
repeatDelay: 1,
ease: Sine.easeInOut
}, 0.5);
};
tween();
setInterval(function() {
tween()
}, 4800);
}
init();
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < dots.length - 1; i++) {
ctx.beginPath();
ctx.moveTo(dots[i].x, dots[i].y);
ctx.lineTo(dots[i + 1].x, dots[i + 1].y);
ctx.lineWidth = 3;
ctx.strokeStyle = 'red';
ctx.stroke();
};
for (var i = 0; i < dots.length; i++) {
ctx.beginPath();
ctx.arc(dots[i].x, dots[i].y, dots[i].r, 0, 2 * Math.PI);
ctx.strokeStyle = dots[i].c;
ctx.lineWidth = 1;
ctx.fillStyle = dots[i].f;
ctx.fill();
ctx.stroke();
ctx.font = dots[i].s + 'px Arial';
ctx.textAlign = 'center';
ctx.fillStyle = '#FFF';
ctx.fillText(dots[i].t, dots[i].x, dots[i].y + 4);
};
setTimeout(function() {
draw();
}, 5);
}
draw();
function hover(e, bool) {
var dot = canvas.getBoundingClientRect();
var x = e.clientX - dot.left;
var y = e.clientY - dot.top;
for (var i = 0; i < rDots.length; i++) {
if (x == rDots[i].x) {
TweenMax.to(rDots[i], 0.1, {
r: 10,
f: 'red',
s: 8
});
$('body').css('cursor', 'pointer');
} else {
TweenMax.to(rDots[i], 0.1, {
r: 3,
f: 'rgba(0,0,0,0)',
s: 0
});
}
};
};
$(canvas).on('mousemove', function(e) {
hover(e, true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" height="100" width="1050" style="background: #EEE"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.1/TweenMax.min.js"></script>
The idea is,
I want it to swing randomly (checked)
and when the cursor close in the knot, it will enlarge and show the text in it...
I tried to use x and y axis to do the trick,
but it doesn't work well...
Then I tried to make another function to draw a bigger circle to cover the original knot,
but since my draw() keeping clear the canvas, so I failed again...
Wondering is there any better ways to make it work?
any suggestions or hints are welcome!
You may find jCanvas helpful.
It's a JavaScript library that wraps the HTML5 canvas API, letting you add certain object-like functionality using a jQuery-style syntax. You could refactor your code a bit and use a mouseOver effect rather than binding a mousemove event to the canvas, which will let you create a smother animation.
Also, if you increase the area of the rDots.x that's triggering your animation and set your Tween time interval to something a bit longer than 0.1 that makes the animation slightly less jerky as well.
Not sure if this solves your issue, but I hope it helps!
Ok, I've work my way out.
$(function() {
'use strict';
var dots = [],
eDots = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100],
rDots = [],
stagger = 0;
var canvas = document.querySelector('#canvas'),
ctx = canvas.getContext('2d');
//initialize all the dots obj
function init() {
for (var i = 0; i < 100; i++) {
if (eDots.indexOf(i) != -1) {
var dot = {
xAxis: stagger,
yAxis: 50,
radius: 3,
color: 'rgba(0,0,0,0)',
num: 1,
};
rDots.push(dot);
} else {
var dot = {
xAxis: stagger,
yAxis: 50,
radius: .5,
color: 'rgba(0,0,0,0)',
num: ''
};
}
dots.push(dot);
stagger += 10;
}
};
init();
//Save position property for click event
function getSize() {
for (var i = 0; i < rDots.length; i++) {
rDots[i].top = rDots[i].yAxis - rDots[i].radius;
rDots[i].right = rDots[i].xAxis + rDots[i].radius;
rDots[i].bottom = rDots[i].yAxis + rDots[i].radius;
rDots[i].left = rDots[i].xAxis - rDots[i].radius;
}
}
getSize();
//Hover event dots to change style
function hover() {
$(canvas).bind('mousemove', function(e) {
var dot = canvas.getBoundingClientRect(),
x = e.clientX - dot.left,
y = e.clientY - dot.top;
for (var i = 0; i < rDots.length; i++) {
ctx.beginPath();
ctx.arc(rDots[i].xAxis, rDots[i].yAxis, rDots[i].radius, 0, 2 * Math.PI);
//rDots[i].radius = ctx.isPointInPath(x, y) ? 10 : 3;
//rDots[i].color = ctx.isPointInPath(x, y) ? 'red' : 'rgba(0, 0, 0, 0)';
if (ctx.isPointInPath(x, y)) {
TweenMax.to(rDots[i], 0.1, {
radius: 10,
color: 'red',
});
$(canvas).css({
cursor: 'pointer'
});
return;
} else {
TweenMax.to(rDots[i], 0.1, {
radius: 3,
color: 'rgba(0,0,0,0)'
});
}
ctx.stroke();
ctx.fill();
$(canvas).css({
cursor: 'default'
});
}
});
};
hover();
//Setup click event for functioning purpose
function click(e) {
var dot = canvas.getBoundingClientRect(),
x = e.clientX - dot.left,
y = e.clientY - dot.top;
for (var i = 0; i < rDots.length; i++) {
if (x < rDots[i].right && x > rDots[i].left && y > rDots[i].top && y < rDots[i].bottom) {
console.log('This is dot ' + i);
}
}
};
$(canvas).on('click', function(e) {
click(e);
})
//Let the line start to twist
function tween() {
var height = Math.floor(Math.random() * (75 - 25) + 25);
TweenMax.staggerTo(dots, 4, {
yAxis: height,
yoyo: true,
repeat: 'repeat',
repeatDelay: 1,
ease: Sine.easeInOut
}, 0.5);
setTimeout(function() {
tween();
}, 3800);
}
tween();
//Let's get some paint
function draw() {
//clear canvas for animate
ctx.clearRect(0, 0, canvas.width, canvas.height);
//draw the lines
for (var i = 0; i < dots.length - 1; i++) {
ctx.moveTo(dots[i].xAxis, dots[i].yAxis);
ctx.lineTo(dots[i + 1].xAxis, dots[i + 1].yAxis);
ctx.lineWidth = 3;
ctx.stroke();
}
//draw the dots
for (var i = 0; i < dots.length; i++) {
ctx.beginPath();
ctx.arc(dots[i].xAxis, dots[i].yAxis, dots[i].radius, 0, 2 * Math.PI);
ctx.strokeStyle = 'red';
ctx.strokeWidth = '1px';
ctx.fillStyle = dots[i].color;
ctx.stroke();
ctx.fill()
};
setTimeout(function() {
draw();
}, 10);
}
draw();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.1/TweenMax.min.js"></script>
<canvas id="canvas" height="100" width="1000" style="background:#EEE"></canvas>
Turn's out all I need is to do is use isPointOnPath to get the path's axis,
then manipulate the certain dot's property with if statement, in my case is it's radius and color.
simple enough...
Can't believe I couldn't figured it out.
I guess I need some sleep now XD

Categories

Resources