How to insert tspan into text-element via javascript [duplicate] - javascript

I have the following code:
var set = paper.set();
var text = paper.text(0, 0, 'bla1 bla2' ).attr({ fill: 'blue'});
set.push(text);
How can I change the color of the 'bla2' to green now?
I've already tried to split the string into two text-elements and assign the coordinates of the 'bla1'+ width of the 'bla1' to the second one. It didn't work since I coundn't find out the width of 'bla1'. The second problem with this solution is that I might want to change the font-size of 'bla1 bla2' which will automatically change the width of 'bla1' and distort the position of 'bla2'.
Thanks in advance!

You can try something like this:
HTML:
<div id="canvas"></div>​
JS:
var text = "this is some colored text";
var paper = Raphael('canvas', '100%', document.documentElement.clientHeight/2 );
var colors = ["#ffc000", "#1d1d1d", "#e81c6e", "#7c7c7c", "#00aff2"];
var letterSpace = 5;
var xPos = 10;
var yPos = 10;
textNodes = text.split(' ');
for( var i=0; i < textNodes.length; ++i) {
var textColor = colors[i];
var textNode = paper.text( xPos , yPos , textNodes[i]);
textNode.attr({
'text-anchor': 'start',
'font-size' : 12,
'fill' : textColor
});
xPos = xPos + textNode.getBBox().width + letterSpace;
}
​
Demo:
http://jsfiddle.net/aamir/zsS7L/

Related

How to give values from array as style to the div

I have bunch of numbers in an array and also I have the same amount div.Now I need to first value from array to gave first div and so on.
var xList = [265, 152, 364]
var yList = [125, 452, 215]
And every div have the same class name
function creatContent(e) {
var divMark = document.createElement("div");
divMark.classList = `markers mark`;
var img = $('<img class="comment" src="indeksiraj-1.png" alt="myimage" />');
$(divMark).append(img);
}
How to first value gave to first div second to the second div and so on.
And I was thinking about using css like this.
$(".markers").css({ top: yList + "px", left: xList + "px" });
Firstly, it appears you are mixing raw JS with JQuery. It is recommended that you avoid JQuery these days as the raw JS methods are just as simple, but significantly quicker, and they have been usable for the last 4 years - that is to say in all the browsers still supported by their manufacturers. I have therefore changed all JQuery bits from your question with raw JS bits in my answer.
Basic answer
Now, the correct way to do what you're asking is to perform that inside of your function. For example:
function createContent(xPos, yPos) {
var divMark = document.createElement('div');
divMark.classList = 'markers mark';
divMark.style.top = yPos + 'px';
divMark.style.left = xPos + 'px';
var img = document.createElement('img');
img.classList = 'comment';
img.src = 'indeksiraj-1.png';
img.alt = 'myimage';
divMark.appendChild(img);
}
Then you'll need to loop over the arrays to call the function.
for (var i = 0; i < xList.length && i < yList.length; i++) {
createContent(xList[i], yList[i]);
}
Further consideration
As a consideration, you could use a single array for the xList and yList, which would allow you to change your loop to something more readable
var posList = [
{x: 265, y: 125},
{x: 152, y: 452},
{x: 364, y: 215},
];
posList.forEach(({x, y}) => {
createContent(x, y);
});
Without changing function signature
Having now seen more context via your fiddle, I can see the createContent function is called from a button click, and does far more than you have included. I have kept my change to remove the JQuery bit from your snippet, and put in a placeholder for you to put in the rest of the functionality in the createContent function.
function createContent(e) {
var divMark = document.createElement('div');
divMark.classList = 'markers mark';
var img = document.createElement('img');
img.classList = 'comment';
img.src = 'indeksiraj-1.png';
img.alt = 'myimage';
divMark.appendChild(img);
// ...put the rest of the code in the funtion here
return divMark;
}
for (var i = 0; i < xList.length && i < yList.length; i++) {
var mark = createContent();
mark.style.top = yList[i] + 'px';
mark.style.left = xList[i] + 'px';
}

Created pdf doesn't make line breaks using jsPDF() [duplicate]

what I'm doing is using jsPDF to create a PDF of the graph I generated. However, I am not sure how to wrap the title (added by using the text() function). The length of the title will vary from graph to graph. Currently, my titles are running off the page. Any help would be appreciated!
This is the code i have so far:
var doc = new jsPDF();
doc.setFontSize(18);
doc.text(15, 15, reportTitle);
doc.addImage(outputURL, 'JPEG', 15, 40, 180, 100);
doc.save(reportTitle);
Nothing to keep the reportTitle from running off the page
Okay I've solved this. I used the jsPDF function, splitTextToSize(text, maxlen, options). This function returns an array of strings. Fortunately, the jsPDF text() function, which is used to write to the document, accepts both strings and arrays of strings.
var splitTitle = doc.splitTextToSize(reportTitle, 180);
doc.text(15, 20, splitTitle);
You can just use the optional argument maxWidth from the text function.
doc.text(15, 15, reportTitle, { maxWidth: 40 });
That will split the text once it reaches the maxWidth and start on the next line.
Auto-paging and text wrap issue in JSPDF can achieve with following code
var splitTitle = doc.splitTextToSize($('#textarea').val(), 270);
var pageHeight = doc.internal.pageSize.height;
doc.setFontType("normal");
doc.setFontSize("11");
var y = 7;
for (var i = 0; i < splitTitle.length; i++) {
if (y > 280) {
y = 10;
doc.addPage();
}
doc.text(15, y, splitTitle[i]);
y = y + 7;
}
doc.save('my.pdf');
To wrap long string of text to page use this code:
var line = 25 // Line height to start text at
var lineHeight = 5
var leftMargin = 20
var wrapWidth = 180
var longString = 'Long text string goes here'
var splitText = doc.splitTextToSize(longString, wrapWidth)
for (var i = 0, length = splitText.length; i < length; i++) {
// loop thru each line and increase
doc.text(splitText[i], leftMargin, line)
line = lineHeight + line
}
If you need to dynamically add new lines you want to access the array returned by doc.splitTextToSize and then add more vertical space as you go through each line:
var y = 0, lengthOfPage = 500, text = [a bunch of text elements];
//looping thru each text item
for(var i = 0, textlength = text.length ; i < textlength ; i++) {
var splitTitle = doc.splitTextToSize(text[i], lengthOfPage);
//loop thru each line and output while increasing the vertical space
for(var c = 0, stlength = splitTitle.length ; c < stlength ; c++){
doc.text(y, 20, splitTitle[c]);
y = y + 10;
}
}
Working Helper function
Here's a complete helper function based on the answers by #KB1788 and #user3749946:
It includes line wrap, page wrap, and some styling control:
(Gist available here)
function addWrappedText({text, textWidth, doc, fontSize = 10, fontType = 'normal', lineSpacing = 7, xPosition = 10, initialYPosition = 10, pageWrapInitialYPosition = 10}) {
var textLines = doc.splitTextToSize(text, textWidth); // Split the text into lines
var pageHeight = doc.internal.pageSize.height; // Get page height, well use this for auto-paging
doc.setFontType(fontType);
doc.setFontSize(fontSize);
var cursorY = initialYPosition;
textLines.forEach(lineText => {
if (cursorY > pageHeight) { // Auto-paging
doc.addPage();
cursorY = pageWrapInitialYPosition;
}
doc.text(xPosition, cursorY, lineText);
cursorY += lineSpacing;
})
}
Usage
// All values are jsPDF global units (default unit type is `px`)
const doc = new jsPDF();
addWrappedText({
text: "'Twas brillig, and the slithy toves...", // Put a really long string here
textWidth: 220,
doc,
// Optional
fontSize: '12',
fontType: 'normal',
lineSpacing: 7, // Space between lines
xPosition: 10, // Text offset from left of document
initialYPosition: 30, // Initial offset from top of document; set based on prior objects in document
pageWrapInitialYPosition: 10 // Initial offset from top of document when page-wrapping
});
When we use linebreak in jsPDF we get an error stating b.match is not defined, to solve this error just unminify the js and replace b.match with String(b).match and u will get this error twice just replace both and then we get c.split is not defined just do the same in this case replace it with String(c).match and we are done. Now you can see line breaks in you pdf. Thank you

Add Link to X-Label Chart.js

I'm looking to be able to link the x-labels in a Chart.js bar chart. I've searched pretty thoroughly, and ended up trying to come up with my own solution: because the labels correspond to the bars directly above them and Chart.js has a built in getBarsAtEvent(evt) method, I tried creating an event if the user didn't click on a chart - this new event had pageX and pageY that was directly above the initial click such that if the user had clicked on a label, the new event would simulate a click on the bar graph.
However, calling getBarsAtEvent(createdClickEvent) repeatedly gives me a Uncaught TypeError ("Cannot read property 'getBoundingClientRect' of null"), which must mean that the getBarsAtEvent method, when called on my simulated click, isn't actually returning anything.
Any suggestions or alternate approaches would be greatly appreciated, thanks in advance.
An alternative approach would be to determine the point where the user is actually clicked and based on that calculate which label was clicked. For that you will need some information about the chart created and have to do some calculations.
Below is a way of doing that, and here is a Fiddle with this code/approach. Hope it helps.
$("#canvas").click(
function(evt){
var ctx = document.getElementById("canvas").getContext("2d");
// from the endPoint we get the end of the bars area
var base = myBar.scale.endPoint;
var height = myBar.chart.height;
var width = myBar.chart.width;
// only call if event is under the xAxis
if(evt.pageY > base){
// how many xLabels we have
var count = myBar.scale.valuesCount;
var padding_left = myBar.scale.xScalePaddingLeft;
var padding_right = myBar.scale.xScalePaddingRight;
// calculate width for each label
var xwidth = (width-padding_left-padding_right)/count;
// determine what label were clicked on AND PUT IT INTO bar_index
var bar_index = (evt.offsetX - padding_left) / xwidth;
// don't call for padding areas
if(bar_index > 0 & bar_index < count){
bar_index = parseInt(bar_index);
// either get label from barChartData
console.log("barChartData:" + barChartData.labels[bar_index]);
// or from current data
var ret = [];
for (var i = 0; i < myBar.datasets[0].bars.length; i++) {
ret.push(myBar.datasets[0].bars[i].label)
};
console.log("current data:" + ret[bar_index]);
// based on the label you can call any function
}
}
}
);
I modified iecs's answer to work with chartjs 2.7.1
var that = this;
this.chart = new Chart($("#chart"), {
type: 'bar',
data: {
labels: labels,
datasets: datasets
},
options: {
events: ["mousemove", "mouseout", "click", "touchstart", "touchmove", "touchend"],
onClick: function(e, data) {
var ctx = $("#chart")[0].getContext("2d");
var base = that.chart.chartArea.bottom;
var height = that.chart.chart.height;
var width = that.chart.chart.scales['x-axis-0'].width;
var offset = $('#chart').offset().top - $(window).scrollTop();
if(e.pageY > base + offset){
var count = that.chart.scales['x-axis-0'].ticks.length;
var padding_left = that.chart.scales['x-axis-0'].paddingLeft;
var padding_right = that.chart.scales['x-axis-0'].paddingRight;
var xwidth = (width-padding_left-padding_right)/count;
// don't call for padding areas
var bar_index = (e.offsetX - padding_left - that.chart.scales['y-axis-0'].width) / xwidth;
if(bar_index > 0 & bar_index < count){
bar_index = Math.floor(bar_index);
console.log(bar_index);
}
}
}
}
});
The main differences are:
The newer versions of chartjs use an chart.scales array instead of chart.scale with a bunch of values
I had to subtract chart.scales['y-axis-0'].width from the x offset to get the correct bar_index
I changed parseInt to Math.floor, just personal preference
And if you want the cursor to change when you hover over them, add "hover" to the events array and this to the options:
onHover: function(e) {
var ctx = $("#chart")[0].getContext("2d");
var base = that.chart.chartArea.bottom;
var height = that.chart.chart.height;
var width = that.chart.chart.scales['x-axis-0'].width;
var yOffset = $('#chart').offset().top - $(window).scrollTop();
var xOffset = $('#chart').offset().left - $(window).scrollLeft();
var left = xOffset + that.chart.scales['x-axis-0'].paddingLeft + that.chart.scales['x-axis-0'].left;
var right = xOffset + that.chart.scales['x-axis-0'].paddingRight + that.chart.scales['x-axis-0'].left + width;
if(e.pageY > base + yOffset && e.pageX > left && e.pageX < right){
e.target.style.cursor = 'pointer';
}
else {
e.target.style.cursor = 'default';
}
}

Gradient fill empty in for loop

I'm drawing buttons on createjs canvas that have gradient fill and stroke. The number of buttons are drawn inside a for loop. Each section, as you will see in the fiddle, is drawn separately via function. but only the first function run draws the correct fill. The subsequent calls only draws the gradient stroke Jsfiddle
for (i = 0; i < db.length; i++) {
var btn = db[i];
var sdb = btn.split("_");
var blabel = sdb[0];
var battrib = sdb[1];
var bval = sdb[2];
var sid = sdb[3];
var tick = sdb[4];
var cptn = sdb[5];
var imageType = sdb[6];
var buttonSize = 90 + 10;
var bttn = new c.Shape();
bttn.graphics.beginLinearGradientFill([grad1, grad2], [.2, 1], 0, 0,0,50 ).setStrokeStyle(3).beginLinearGradientStroke([grad2, grad1], [.2, 1], 0, 0,0,50 ).drawRoundRect(x, y, 85, 35,5);
var label = new c.Text(blabel);
label.font = font;
label.color = '#000';
label.x = x+8;
label.y = y+6;
m1.addChild(bttn, label);
x+= buttonSize;
}s.update();
It seems to be working to me. Is it perhaps that you forgot to offset your buttons, so you're only seeing the first one? bttn.y = i*40
https://jsfiddle.net/gskinner/wqu4nzdq/12/

RaphaelJs: How to animate a path after translate

I'm trying to animatate a spinning star icon:
var star = this._paper.path("M26.522,12.293l-5.024-0.73c-1.089-0.158-2.378-1.095-2.864-2.081l-2.249-4.554c-0.487-0.986-1.284-0.986-1.771,0l-2.247,4.554c-0.487,0.986-1.776,1.923-2.864,2.081l-5.026,0.73c-1.088,0.158-1.334,0.916-0.547,1.684l3.637,3.544c0.788,0.769,1.28,2.283,1.094,3.368l-0.858,5.004c-0.186,1.085,0.458,1.553,1.432,1.041l4.495-2.363c0.974-0.512,2.566-0.512,3.541,0l4.495,2.363c0.974,0.512,1.618,0.044,1.433-1.041l-0.859-5.004c-0.186-1.085,0.307-2.6,1.095-3.368l3.636-3.544C27.857,13.209,27.611,12.452,26.522,12.293zM22.037,16.089c-1.266,1.232-1.966,3.394-1.67,5.137l0.514,2.984l-2.679-1.409c-0.757-0.396-1.715-0.612-2.702-0.612s-1.945,0.216-2.7,0.61l-2.679,1.409l0.511-2.982c0.297-1.743-0.404-3.905-1.671-5.137l-2.166-2.112l2.995-0.435c1.754-0.255,3.592-1.591,4.373-3.175L15.5,7.652l1.342,2.716c0.781,1.583,2.617,2.92,4.369,3.173l2.992,0.435L22.037,16.089z")
.attr({ fill: "darkred", stroke: "none" })
.transform("t"+starX+","+starY);
var a0 = Raphael.animation({ transform: "r360"}, 2000);
star.animate(a0.repeat(Infinity));
If I remove the translate I get a nice animation. But with the translate the animation is weird.
The parameters for the animation should include the translation as well, since they are the end attributes of the object, not just the difference between the start and the end ones. See the example: http://jsfiddle.net/b9akz/32/.
var paper = new Raphael('holder');
var starX = 100, starY = 100;
var star = paper.path("M26.522,12.293l-5.024-0.73c-1.089-0.158-2.378-1.095-2.864-2.081l-2.249-4.554c-0.487-0.986-1.284-0.986-1.771,0l-2.247,4.554c-0.487,0.986-1.776,1.923-2.864,2.081l-5.026,0.73c-1.088,0.158-1.334,0.916-0.547,1.684l3.637,3.544c0.788,0.769,1.28,2.283,1.094,3.368l-0.858,5.004c-0.186,1.085,0.458,1.553,1.432,1.041l4.495-2.363c0.974-0.512,2.566-0.512,3.541,0l4.495,2.363c0.974,0.512,1.618,0.044,1.433-1.041l-0.859-5.004c-0.186-1.085,0.307-2.6,1.095-3.368l3.636-3.544C27.857,13.209,27.611,12.452,26.522,12.293zM22.037,16.089c-1.266,1.232-1.966,3.394-1.67,5.137l0.514,2.984l-2.679-1.409c-0.757-0.396-1.715-0.612-2.702-0.612s-1.945,0.216-2.7,0.61l-2.679,1.409l0.511-2.982c0.297-1.743-0.404-3.905-1.671-5.137l-2.166-2.112l2.995-0.435c1.754-0.255,3.592-1.591,4.373-3.175L15.5,7.652l1.342,2.716c0.781,1.583,2.617,2.92,4.369,3.173l2.992,0.435L22.037,16.089z")
.attr({ fill: "darkred", stroke: "none" })
.translate(starX,starY);
var a0 = Raphael.animation({ transform: "t"+starX + "," + starY + " r360"}, 2000);
star.animate(a0.repeat(Infinity));​
You need to factor in the translation in the animate as follows:
var paper = Raphael(0,0,500,500);
var starX = 50;
var starY = 50;
// code for your path here as its rather long! Including your translate
// using the starX and starY
// then the animation
var a0 = Raphael.animation({ transform: "t"+starX+","+starY+"r360"}, 2000);
star.animate(a0.repeat(Infinity));​
I also made a jsfiddle example here for you to see.

Categories