Is it possible to change color of one pixel inside rectangle created with KineticJS? - colors

This is my code:
var Editor = {
layer: new Kinetic.Layer(),
map: null,
init: function () {
var stage = new Kinetic.Stage({
container: 'board',
width: 800,
height: 800
})
this.map = new Kinetic.Shape({
sceneFunc: function(context) {
context.beginPath();
context.moveTo(0, 0);
context.lineTo(mapWidth, 0);
context.lineTo(mapWidth, mapHeight);
context.lineTo(0, mapHeight);
context.closePath();
context.fillStrokeShape(this);
},
x: 0,
y: 0,
fill: 'green',
draggable: true
})
this.layer.add(this.map)
stage.add(this.layer)
}
}
I want to change the colors of the pixels in the rectangle. Colors of pixels will be generated by the "diamond-square" algorithm. Is it possible to change the colors of individual pixels? If so, how can I do this?

[ Changed answer ]
Use an offscreen html canvas to overlay the pixels in your "diamond-square" algorithm.
Demo: http://jsfiddle.net/m1erickson/6mDSm/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.0.1.min.js"></script>
<style>
body{padding:20px;}
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:350px;
height:350px;
}
</style>
<script>
$(function(){
var stage = new Kinetic.Stage({
container: 'container',
width: 350,
height: 350
});
var layer = new Kinetic.Layer();
stage.add(layer);
var mapWidth=50;
var mapHeight=75;
// use an offscreen canvas as a pixel-map overlaying the green map
var pixelCanvas=document.createElement("canvas");
var ctx=pixelCanvas.getContext("2d");
pixelCanvas.width=mapWidth;
pixelCanvas.height=mapHeight;
pixelCanvas.pixels=[]
pixelCanvas.setPixel=function(x,y,color){
ctx.fillStyle=color;
ctx.fillRect(x,y,1,1);
};
// create a group
// that holds the green map background and pixel-map overlay
var mapGroup=new Kinetic.Group({
x:30,
y:30,
width:mapWidth,
height:mapHeight,
draggable:true
});
layer.add(mapGroup);
// the green background
var map=new Kinetic.Rect({
x:0,
y:0,
width:mapWidth,
height:mapHeight,
fill:"green"
});
mapGroup.add(map);
// an image overlay that
// gets "live-updates" from an offscreen canvas
var pixels=new Kinetic.Image({
x:0,
y:0,
image:pixelCanvas
});
mapGroup.add(pixels);
layer.draw();
// testing
var y=15;
$("#add").click(function(){
for(var i=0;i<5;i++){
pixelCanvas.setPixel(15,y,"red");
pixelCanvas.setPixel(25,y,"gold");
pixelCanvas.setPixel(35,y++,"blue");
}
pixels.draw();
});
}); // end $(function(){});
</script>
</head>
<body>
<button id="add">Add test Pixels</button>
<div id="container"></div>
</body>
</html>
Note: my previous answer using Kinetic.Shape was leaving an undesirable "ghost"

Related

Cytoscape Cola Layout: How to restart the layout without any change of positions?

I'm trying to use the Cytoscape cola layout to render a graph that should apply a force directed layout while using it (so when dragging nodes around, they should act as if there is some gravity involved).
Relevant libraries:
https://github.com/cytoscape/cytoscape.js
https://github.com/tgdwyer/WebCola
https://github.com/cytoscape/cytoscape.js-cola
My first problem is that adding nodes to the graph via add(node) doesn't include them in the cola layout algorithm. The only way I found around that is to destroy the layout, re-initialize it and start it again. But this causes the nodes to jump in some cases.
I assumed that this was due to the fact that I completely destroyed the old layout but when setting up a minimal example, I realized that even just calling layout.stop() and layout.run() leads to nodes being repositioned.
In the following example, there is only one node. Moving the node via drag and drop, then pressing the "stop" button and then the "start" button causes the node to jump back to its initial position:
document.addEventListener('DOMContentLoaded', function(){
// Register cola layout
cytoscapeCola(cytoscape);
var nodes = [{ data: { id: 1, name: 1 } }]
var edges = [];
var cy = window.cy = cytoscape({
container: document.getElementById('cy'),
style: [
{
selector: 'node[name]',
style: {
'content': 'data(name)'
}
},
{
selector: 'edge',
style: {
'curve-style': 'bezier',
'target-arrow-shape': 'triangle'
}
},
],
elements: {
nodes: nodes,
edges: edges
}
});
var layout = cy.layout({
name: 'cola',
infinite: true,
fit: false,
});
layout.run();
document.querySelector('#start').addEventListener('click', function() {
layout.run();
});
document.querySelector('#stop').addEventListener('click', function() {
layout.stop();
});
document.querySelector('#add-node').addEventListener('click', function() {
var id = Math.random();
cy.add({ group: 'nodes', data: { id: id, name: id } });
cy.add({ group: 'edges', data: { source: id, target: _.head(nodes).data.id } });
layout.stop();
layout.destroy();
layout = cy.layout({
name: 'cola',
infinite: true,
fit: false,
});
layout.run();
});
});
body {
font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
font-size: 14px;
}
#cy {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
z-index: 999;
}
h1 {
opacity: 0.5;
font-size: 1em;
font-weight: bold;
}
#buttons {
position: absolute;
right: 0;
bottom: 0;
z-index: 99999;
}
<!DOCTYPE>
<html>
<head>
<title>cytoscape-edgehandles.js demo for infinite layout</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>
<script src="https://unpkg.com/webcola/WebCola/cola.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/cytoscape-cola#2.4.0/cytoscape-cola.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
<script src="cytoscape-edgehandles.js"></script>
</head>
<body>
<h1>cytoscape-edgehandles demo with an infinite layout</h1>
<div id="cy"></div>
<div id="buttons">
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="add-node">Add Node</button>
</div>
</body>
</html>
Is this a bug or am I doing something wrong? Does anyone know how to stop and restart the layout without the nodes changing their position?
Thanks a lot,
Jesse
Okay actually you were very close #Stephan.
The problem was that WebCola centers the nodes when calling start by default:
https://github.com/tgdwyer/WebCola/blob/78a24fc0dbf0b4eb4a12386db9c09b087633267d/src/layout.ts#L504
The cytoscape wrapper for WebCola does not currently support this option, so I forked it and added the option myself:
https://github.com/deje1011/cytoscape.js-cola/commit/f357b97aba900327e12f97b1530c4df624ff9d61
I'll open a pull request at some point.
Now you can smoothly restart the layout like this:
layout.stop();
layout.destroy(); // cleanup event listeners
layout = graph.layout({ name: 'cola', infinite: true, fit: false, centerGraph: false });
layout.run()
This way, the nodes keep their position 🎉

Center Fabricjs iText produces a blurry effect

I'm trying to add an IText element to the center of the canvas, but when I call the canvas.centerObject(object) method, the text gets blurred.
You have an example in this fiddle.
var canvas = new fabric.Canvas('canvas',{
width:400,
height:400
});
canvas.setBackgroundColor('#f4f2f2', canvas.renderAll.bind(canvas));
$('#add-text-btn').click(function() {
var text = new fabric.IText('Tap and Type', {
fill: '#333',
fontSize: 14,
});
canvas.add(text);
})
$('#add-ugly-text-btn').click(function() {
var text = new fabric.IText('Tap and Type', {
fill: '#333',
fontSize: 14,
});
canvas.add(text);
//canvas.centerObject(text);
text.center();
text.setCoords();
canvas.renderAll();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.2.3/fabric.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add-text-btn">Add text</button>
<button id="add-ugly-text-btn">Add centered text</button><br>
<canvas id="canvas"></canvas>

setText() not working in fabricjs version 2

I am trying to set text to textbox explicitly,in older fabricjs versionobject.setText("something")
was working but not working in fabric js version 2. Any other way introduced in this version?
var canvas = new fabric.Canvas('c');
var text1 = new fabric.Textbox('Text', {
left: 10,
top: 20,
width: 300
})
canvas.add(text1);
canvas.on('text:changed', function(e) {
var objTEmp = e.target;
objTEmp.setText("some");
});
canvas{
border:1px solid #000;
}
<script type="text/javascript" src="
https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.0.0-rc.4/fabric.js"></script>
<canvas id="c" width="400" height="400" style="border:1px solid #000000;"></canvas>
That build doesn't have setter/getter (optional). If you want to set text you can use
obj.text = text;
//or
obj.set({
text:text
});
//or
obj.set('text', text);
DEMO
var canvas = new fabric.Canvas('c');
var text1 = new fabric.Textbox('Text', {
left: 10,
top: 20,
width: 300
})
canvas.add(text1);
canvas.on('text:changed', function(e) {
var objTEmp = e.target;
objTEmp.set({
text : "some"
});
});
canvas{
border:1px solid #000;
}
<script type="text/javascript" src="
https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.0.0-rc.4/fabric.js"></script>
<canvas id="c" width="400" height="400" style="border:1px solid #000000;"></canvas>
You can build your own version of Fabric.js here: http://fabricjs.com/build/
Check "Named accessors" to bring back support for setters and getters. Not recommended and unsupported, who knows how long it will stay in there, but if you just need a quick solution now, that will do the trick.

canvas background turns black after rerender fabric.js

I have the following situation: I draw the canvas with a background image and this works:
var canvasSection = new fabric.Canvas('buildSection', {
selectionColor: 'rgba(94,213,94,0.2)',
width: widthS,
height: heightS,
hoverCursor: 'pointer',
backgroundColor: ({
source: 'image/bordenconfigurator/background/background1.png',
repeat: 'repeat'
})
});
But then I need to clear canvas and to redraw it. at this point when I try to set background, instead of an image I see a black screen. In console I can see that the background image is set however. This is the code I'm trying:
$('#cForm').on('change', function() {
if ($(this).val() == 'rectLandsc') {
widthS = 600;
heightS = 400;
} else if ($(this).val() == 'rectPortr') {
....
}
canvasSection.clear();
canvasSection.set({
fill: 'rgba(0,0,0,0)',
// backgroundColor: ({source: 'image/bordenconfigurator/background/background1.png', repeat: 'repeat'})
});
//canvasSection.backgroundColor({source: 'image/bordenconfigurator/background/background.png', repeat:'repeat'});
canvasSection.setBackgroundColor({
source: 'image/bordenconfigurator/background/background.png'
}),
canvasSection.renderAll.bind(canvas);
drawBaseForm();
canvasSection.renderAll();
console.log(canvasSection);
});
Is it a kind of a bug? Or am I doing something wrong? Could anyone help me out here?
canvas.setBackgroundColor({
source: 'image/bordenconfigurator/background/background1.png',
repeat: 'repeat'
}, canvas.renderAll.bind(canvas));
setBackgroundColor first parameter is color/pattern and second parameter is callback function.
DEMO
var canvas = new fabric.Canvas('c');
canvas.setBackgroundColor({
source: 'http://fabricjs.com/assets/pug_small.jpg'
}, canvas.renderAll.bind(canvas));
function clearCanvas(){
var background = canvas.backgroundColor;
canvas.clear();
setTimeout(function(){
canvas.setBackgroundColor(background,canvas.renderAll.bind(canvas));
},2000)
}
canvas{
border: 2px dotted black;
}
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<button onclick='clearCanvas()'>clear</button>
<canvas id="c" width="500" height="500"></canvas>

How to justify text in kinetic.js text object?

Kinetic Text object have left,right,center (http://kineticjs.com/docs/Kinetic.Text.html) align possible. Is there some way to achieve justified text ?
KineticJS is based on the html canvas element and canvas does not offer text justification.
You could construct your own text justification routine using canvas's context.measureText to measure the width of each word and fill each line of text in a justified pattern.
Example code and a Demo: http://jsfiddle.net/m1erickson/c7dwC/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.0.1.min.js"></script>
<style>
body{padding:20px;}
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:350px;
height:350px;
}
</style>
<script>
$(function(){
function Justifier(text,font,linewidth,lineheight){
//
this.font=font;
this.lorem=text;
this.maxLineWidth=linewidth;
this.lineHeight=lineheight;
//
this.canvas=document.createElement("canvas");
this.ctx=this.canvas.getContext("2d");
this.aLorem=this.lorem.split(" ");
this.aWidths=[];
this.spaceWidth;
//this.run();
}
Justifier.prototype.run=function(){
this.ctx.save();
this.ctx.font=this.font;
spaceWidth=this.ctx.measureText(" ").width;
for(var i=0;i<this.aLorem.length;i++){
this.aWidths.push(this.ctx.measureText(this.aLorem[i]).width);
}
this.ctx.restore();
//
var justifiedLines=[];
var startingIndex=0;
do{
var line=this.justifyLine(startingIndex);
justifiedLines.push(line);
startingIndex=line.endingIndex+1;
}while(startingIndex<this.aLorem.length-1);
//
this.canvas.width=this.maxLineWidth;
this.canvas.height=justifiedLines.length*this.lineHeight+5;
this.ctx.font=this.font;
for(var i=0;i<justifiedLines.length;i++){
this.drawJustifiedLine(justifiedLines[i],i*this.lineHeight+this.lineHeight);
}
}
Justifier.prototype.justifyLine=function(startingIndex){
var accumWidth=0;
var accumWordWidth=0;
var padding=0;
var justifiedPadding;
var index=startingIndex;
while(index<this.aLorem.length && accumWidth+padding+this.aWidths[index]<=this.maxLineWidth){
accumWidth+=padding+this.aWidths[index];
accumWordWidth+=this.aWidths[index];
padding=spaceWidth;
index++;
};
if(index<this.aWidths.length-1){
index--;
justifiedPadding=(this.maxLineWidth-accumWordWidth)/(index-startingIndex);
}else{
justifiedPadding=(this.maxLineWidth-accumWordWidth)/(index-startingIndex-1);
}
return({
startingIndex:startingIndex,
endingIndex:index,
justifiedPadding:justifiedPadding}
);
}
Justifier.prototype.drawJustifiedLine=function(jLine,y){
var sp=jLine.justifiedPadding;
var accumLeft=0;
for(var i=jLine.startingIndex;i<=jLine.endingIndex;i++){
this.ctx.fillText(this.aLorem[i],accumLeft,y);
accumLeft+=this.aWidths[i]+sp;
}
}
var stage = new Kinetic.Stage({
container: 'container',
width: 350,
height: 350
});
var layer = new Kinetic.Layer();
stage.add(layer);
var font="14px verdana";
var text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.";
var J=new Justifier(text,font,250,18);
J.run();
var textImage=new Kinetic.Image({
x:20,
y:20,
image:J.canvas,
draggable:true,
});
layer.add(textImage);
layer.draw();
}); // end $(function(){});
</script>
</head>
<body>
<h4>KineticJS Justified Text</h4>
<div id="container"></div>
</body>
</html>

Resources