how to recognize point(x y) is inside svg group geometry elements - javascript

as my code (whether a point is inside an element like rectangle, polygon, polyline, line, circle) is working perfectly but if I want to implement this one for the group element of rectangle, polygon, polyline, line, circle, then it does not work (means isPointInFill() or isPointInStroke() does not work for the group Id).
I would be grateful if someone help me solving this.
--------------------------------------------------------
const width = document.getElementById("svgID").viewBox.baseVal.width;
const height = document.getElementById("svgID").viewBox.baseVal.height;
let draw = Snap('#svg');
let c = 0; // a counter for each generated element
let count = 0; // counter for rows
let size = Math.round(0.05 * width);
let circleSize = 25;
let circleColor = ["#ff0000", "#000000", "#00ffe1", "#0051ff"];
for (let i = 0; i <= width; i = i + size) {
count++;
for (let j = 0; j <= height; j = j + size) {
// increment our element counter
c += 1;
let rect = draw.rect(i, j, size, size);
let circle4 = draw.circle(i + (size / 2), j + (size / 2), circleSize);
circle4.attr({
fill: circleColor[3],
"fill-opacity": 1,
stroke: "#000",
"stroke-width": "1px",
id: "circle4_" + c,
name: "circle4_" + c
});
rect.attr({
fill: "#d00bf3",
"fill-opacity": 0.2,
stroke: "#000",
"stroke-width": "1px",
id: "rect_" + c,
name: "rect" + c
});
const circleID = document.getElementById(`circle4_${c}`);
//for individual element id:
/*let element_ids = ["polygon870", "polygon36458", "polygon34", "polygon38"];*/
//for group id:
let element_ids = ["g5523", "g5526", "g5529", "g5532", "g5535", "g5538" ];
//let b_062 = document.getElementById("b_06.2");
let point = {x: circleID.cx.baseVal.value, y: circleID.cy.baseVal.value};
/*let point = document.getElementById("svgId").createSVGPoint();
point.x = circleID.cx.baseVal.value;
point.y = circleID.cy.baseVal.value;*/
//console.log(`Point at ${point.x}, ${point.y}:`, polygon870.isPointInStroke(point));
//console.log(`Point at ${point.x}, ${point.y}:`, polygon36458.isPointInStroke(point));
//console.log(`Point at ${point.x}, ${point.y}:`, b_062.isPointInFill(new DOMPoint(point.x, point.y)));
/*let result = g5523.isPointInFill(205, 205);
console.log(`Point at (${point.x}, ${point.y})- (circleID: ${result}`);*/
for (let id of element_ids) {
let result = document.getElementById(id).isPointInFill(new DOMPoint(point.x, point.y));
let result2 = document.getElementById(id).isPointInStroke(new DOMPoint(point.x, point.y));
if (result) {
console.log(`Point at (${point.x}, ${point.y})- (circleID: ${circleID.id}): ${result}`);
console.log(`Point at (${point.x}, ${point.y})- (circleID: ${circleID.id}): ${result2}`);
}
}
}
}

Related

Paper.js How can I make colorful strokeColor?

I have a problem. I can't make a colorful strokeColor. I tried to do like that
p.strokeColor = 'purple'; p.strokeColor = 'red'; and p.strokeColor=['purple','red'].
But nothing helps. Here's an example.
Here's a demo. https://codepen.io/aqua908/pen/rNvyyJj
You are doing fine, only choose different color every time, say according to y
if (y % 2 == 0) {
p.strokeColor = "purple";
} else {
p.strokeColor = "blue";
}
window.onload = function () {
var w = 800; //window.innerWidth
var h = 400; //window.innerHeight
var params = {
height: 0.3,
amplitude: 60,
speedX: 5,
speedY: 5,
speedZ: 5,
frequenceX: 2,
frequenceY: 2,
frequenceZ: 5
};
var gui = new dat.gui.GUI();
var f1 = gui.addFolder("Noise Waves");
f1.add(params, "height", 0.1, 1).step(0.1);
f1.add(params, "amplitude", 0, 150).step(1);
f1.add(params, "speedX", -10, 10).step(0.5);
f1.add(params, "speedY", -10, 10).step(0.5);
f1.add(params, "speedZ", -10, 10).step(0.5);
f1.add(params, "frequenceX", 1, 10);
f1.add(params, "frequenceY", 1, 10);
f1.add(params, "frequenceZ", 1, 10);
f1.open();
var simplex = new SimplexNoise();
var nx = 0;
var ny = 0;
var nz = 0;
var cols = 256;
var rows = 16;
var primitives = [];
paper.install(window);
paper.setup("myCanvas");
for (var y = 0; y < rows; y++) {
var p = new Path();
p.segments = [];
for (var x = 0; x < cols; x++) {
p.add(new Point(2, h / 2));
}
if (y % 2 == 0) {
p.strokeColor = "purple";
} else {
p.strokeColor = "blue";
}
p.strokeWidth = 2;
//p.smooth({ type: 'continuous' })
primitives.push(p);
}
view.onFrame = function (event) {
nx += params.speedX / 1000;
ny += params.speedY / 1000;
nz += params.speedZ / 100;
for (var y = 0; y < rows; y++) {
var p = primitives[y];
for (var x = 0; x < cols; x++) {
var Y =
(h * (1 - params.height)) / 2 +
((h * params.height) / rows) * y +
simplex.noise3D(
nx + (x * params.frequenceX) / 100,
ny + (y * params.frequenceY) / 100,
(nz * params.frequenceZ) / 100
) *
params.amplitude;
p.segments[x].point.x = (w / cols) * x;
p.segments[x].point.y += 0.1 * (Y - p.segments[x].point.y);
}
}
};
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/simplex-noise/2.3.0/simplex-noise.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.22/paper.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.0-0/dat.gui.js"></script>
<canvas id="myCanvas" width="400" height="200"></canvas>
Define an array containing the colors outside the for loop.
let colors = ['purple', 'red', 'blue', 'yellow']
In your for loop use the iteration index (in your case y) to pick a color from the array.
p.strokeColor = colors[y % colors.length];
use module % when the number of lines is greater than the length of the colors array.

How to make background animation wave with JavaScript?

I want to make a background animation wave like this website hero section. https://raze.network/
Could anyone help me to make this animation background wave?
Thank you :)
There is a great example on codepen that you can use to get a general idea on how to animate this wave using JavaScript. The author allows commenting on CodePen so I would get in touch with him.
let noise = new SimplexNoise();
function draw(e) {
let xCount = 35;
let yCount = 80;
let iXCount = 1 / (xCount - 1);
let iYCount = 1 / (yCount - 1);
let time = e * 0.001;
let timeStep = 0.01;
let grad = ctx.createLinearGradient(-width, 0, width, height);
let t = time % 1;
let tSide = floor(time % 2) === 0;
let hueA = tSide ? 340 : 210;
let hueB = !tSide ? 340 : 210;
let colorA = hsl(hueA, 100, 50);
let colorB = hsl(hueB, 100, 50);
grad.addColorStop(map(t, 0, 1, THIRD, ZERO), colorA);
grad.addColorStop(map(t, 0, 1, TWO_THIRDS, THIRD), colorB);
grad.addColorStop(map(t, 0, 1, ONE, TWO_THIRDS), colorA);
ctx.globalAlpha = map(cos(time), -1, 1, 0.15, 0.3);
background(grad);
ctx.globalAlpha = 1;
beginPath();
for(let j = 0; j < yCount; j++) {
let tj = j * iYCount;
let c = cos(tj * TAU + time) * 0.1;
for(let i = 0; i < xCount; i++) {
let t = i * iXCount;
let n = noise.noise3D(t, time, c);
let y = n * height_half;
let x = t * (width + 20) - width_half - 10;
(i ? lineTo : moveTo)(x, y);
}
time += timeStep;
}
compositeOperation(compOper.lighter);
ctx.filter = 'blur(10px)';
stroke(grad, 5);
ctx.filter = 'blur(5px)';
stroke(hsl(0, 0, 100, 0.8), 2);
}
https://codepen.io/Alca/pen/gzxXLq

Clear and re-draw using svg.js

I want to draw some elements using svg.js then clear the canvas and draw new elements. I'm using draw.clear() but when I re-draw the elements, they aren't visible. Is this approach correct or am I missing something? I also tried remove().
var width = 500;
var height = 500;
var pos_x = 0;
var pos_y = 0;
var texto = [];
var grupo = [];
var rect = [];
var clip = [];
var random_rotation = [];
var latino = 'ABCDEFGHIJKLMNOPQRSTUVXYZ'.split('');
var cirilico = 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЬЮЯ'.split('');
var hebreo = 'אבגדהוזיךכל םמןנסעףפפצקחט '.split('');
var griego = 'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨ'.split('');
var arabe = 'ابتثجحخدذرزسشصضطظعغفقكلمنهويةءأإ'.split('');
var coreano = 'ㅏㅑㅓㅕㅗㅛㅜㅠㅡㅣㅐㅒㅔㅖㅘㅙㅚㅝㅞㅟㅢㄱㄴㄷㄹㅁㅂㅅㅇㅈㅊㅋㅌㅍㅎㄲㄸㅃㅆㅉㄳㄵㄶㄺㄻㄿㄽㄾㄿㅀㅄ'.split('');
var glagolitico = 'ⰀⰁⰂⰃⰄⰅⰆⰇⰈⰉⰊⰋⰌⰍⰎⰏⰐⰑⰒⰓⰔⰕⰖⰗⰘⰙⰚⰛⰜⰝⰞⰟⰠⰡⰢⰣⰤⰥⰦⰧⰨⰩⰪⰫⰬⰭⰮ'.split('');
var hiragana = 'あかさたなはまやらわがざだばぱいきしちにひみり(ゐ)ぎじぢびぴうくすつぬふむゆるぐずづぶぷえけせてねへめれ(ゑ)げぜでべぺおこそとのほもよろをごぞどぼぽ'.split('');
var katakana = 'アカサタナハマヤラワガザダバパヴァイキシチニヒミリ(ヰ)ギジヂビピヴィウクスツヌフムユルグズヅブプヴエケセテネヘメレ(ヱ)ゲゼデベペヴェオコソトノホモヨロヲゴゾドボポヴォ'.split('');
var sistemas = [latino, cirilico, hebreo, griego, arabe, coreano, glagolitico, hiragana, katakana];
var alfabeto = [];
var letra = [];
var draw = SVG().addTo('.container').size(width, height).attr({id: 'svg'});
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getRndFloat(min, max) {
return (Math.random() * (max - min)) + min;
}
// Create symbols
function grafema(){
for (var i = 0; i <= 3; i++){
alfabeto[i] = getRndInteger(0, sistemas.length - 1);
letra[i] = sistemas[alfabeto[i]][getRndInteger(0, sistemas[alfabeto[i]].length - 1)];
random_rotation[i] = getRndInteger(0, 360);
texto[i] = draw.text(letra[i])
.font({
family: 'Arial Unicode MS',
size: 500,
anchor: 'middle'
})
.transform({
translateX: width/2,
translateY: (height/2) * -1,
rotate: random_rotation[i],
scale: getRndFloat(0.5, 0.6)
});
grupo[i] = draw.group()
.attr({
id: 'letra ' + i
});
grupo[i].add(texto[i]);
rect[i] = draw.rect(200, 200)
.attr({
x: pos_x,
y: pos_y,
})
.transform({
rotate : random_rotation[i],
});
pos_x = pos_x + 200;
if (pos_x > 200) {
pos_x = 0;
pos_y = pos_y + 200;
}
clip[i] = draw.clip().add(rect[i]);
grupo[i].clipWith(clip[i]);
}
}
grafema();
draw.clear();
grafema();
This is a simplified version of a program I'm trying to create. In the future I would like to clear and re-draw whenever the user makes a click.
The problem in your code is not the clear() method. You are using global variables pos_x and pos_y and you are incrementing them. In your second drawing, the images are outside the visible area. To solve your issue, initialise those variables in the beginning of your grafema function:
// ...
function grafema() {
pos_x = 0;
pos_y = 0;
for (var i = 0; i <= 3; i++) {
// ...
Example of execution with infinite drawings:
https://jsbin.com/mehuholiwo/edit?js,output

Can this script be used to create multiple SVG elements?

I have the following JavaScript that creates a graph using snap SVG.
However I need to create 4 SVG's in total and I was wondering if I could use only this script for it? And if so, how would I go about adjusting it? Or is it necessary with 4 seperate scripts to create the 4 SVG's?
In short; what's the best way going about this?
Thanks in advance.
The script:
//#SVG
var price = [0,-50, -100, -130, -150, -200];
//CHART VALUES
var chartH = $('#svg').height();
var chartW = $('#svg').width();
// PARSE PRICES TO ALIGN WITH BOTTOM OF OUR SVG
var prices = [];
for (i = 0; i < price.length; i++) {
prices[i] = price[i] + $('#svg').height();
}
function draw() {
//DEFINE SNAP SVG AND DETERMINE STEP NO.
var paper = Snap('#svg');
var steps = prices.length;
// EVENLY DISTRIBUTE OUR POINTS ALONG THE X AXIS
function step(i, chartW) {
return chartW / prices.length * i;
}
var points = [];
var breakPointsX = [];
var breakPointsY = [];
var point = {};
for (i = 1; i < prices.length; i++) {
//CALCULATE CURRENT POINT
var currStep = step(i, chartW);
var y = prices[i];
point.x = Math.floor(currStep);
point.y = y;
//CALCULATE PREVIOUS POINT
var prev = i - 1;
var prevStep = step(prev, chartW);
var prevY = prices[prev];
point.prevX = Math.floor(prevStep);
point.prevY = prevY;
if (point.prevX === 0 || point.prevY === 0){
point.prevX = 15;
point.prevY = chartH - 0
}
// SAVE PATH TO ARRAY
points[i] = " M" + point.prevX + "," + point.prevY + " L" + point.x + "," + point.y;
// SAVE BREAKPOINTS POSITION
var r = 30;
breakPointsX[i] = point.x;
breakPointsY[i] = point.y;
}
// DRAW LINES
for (i = 0; i < points.length; i++) {
var myPath = paper.path(points[i]);
var len = myPath.getTotalLength();
myPath.attr({
'stroke-dasharray': len,
'stroke-dashoffset': len,
'stroke': '#3f4db3',
'stroke-linecap': 'round',
'stroke-width': 6,
'stroke-linejoin': 'round',
'id': 'myLine' + i,
'class': 'line'
});
}
// DRAW BREAKPOINTS
for (i = 0; i < points.length; i++) {
var circle = paper.circle(breakPointsX[i], breakPointsY[i], 5);
circle.attr({
'fill': '#fff',
'stroke': '#3f4db3',
'stroke-width': 3,
'id': 'myCirc' + i,
'class':'breakpoint'
});
}
// DRAW COORDINATE SYSTEM
var xAxis = paper.path('M0,'+chartH+'L'+chartW+","+chartH);
var yAxis = paper.path('M0,'+chartH+'L0,0');
var xOff = xAxis.getTotalLength();
var yOff = yAxis.getTotalLength();
var start = (prices.length*250+"ms");
yAxis.attr({
'stroke':'black',
'stroke-width':10,
'stroke-dasharray':yOff,
'stroke-dashoffset':yOff,
'id':'yAxis'
});
xAxis.attr({
'stroke':'black',
'stroke-width':5,
'stroke-dasharray':xOff,
'stroke-dashoffset':xOff,
'id':'xAxis'
});
console.log(start);
$('#yAxis').css({
'-webkit-transition-delay':start,
'-webkit-transition':'all 200ms ease-in'
});
$('#xAxis').css({
'-webkit-transition-delay':start,
'-webkit-transition':'all 200ms ease-in'
});
$('#xAxis').animate({
'stroke-dashoffset':'0'
});
$('#yAxis').animate({
'stroke-dashoffset': '0'
});
}
function animate(){
for (i=0;i<prices.length;i++){
var circ = $('#myCirc'+i);
var line = $('#myLine'+i);
circ.css({
'-webkit-transition':'all 550ms cubic-bezier(.84,0,.2,1)',
'-webkit-transition-delay':375+(i*125)+"ms"
});
line.css({
'-webkit-transition':'all 250ms cubic-bezier(.84,0,.2,1)',
'-webkit-transition-delay':i*125+"ms"
});
line.animate({
'stroke-dashoffset':0
});
circ.css({
'transform':'scale(1)'
});
}
}
var alreadyPlayed = false;
$(window).load(function(){
draw();
animate();
});

Adding grid over Fabric.js canvas

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();
}

Categories

Resources