Adding gradient text in createjs - html5-canvas

I am currently looking for a way to add a gradient to my text object that was generated with textjs.
this.text = new createjs.Text(this.val, this.font, "#efa146");
this.text.textAlign = "center";
this.text.y = this.pos.y;
this.text.x = this.pos.x;
console.log(this.text);
window.stage.addChild(this.text);

It's actually very easy, just extend the Text object like this
<script>
(function () {
function GradientText(text, font, color) {
this.Text_constructor(text, font, color);
}
var p = createjs.extend(GradientText, createjs.Text);
p._drawTextLine = function (ctx, text, y) {
if (this.gradient) {
var height = this.getMeasuredLineHeight();
var my_gradient = ctx.createLinearGradient(0, y, 0, y + height);
my_gradient.addColorStop(0, "black");
my_gradient.addColorStop(1, "white");
ctx.fillStyle = my_gradient;
ctx.fillText(text, 0, y, this.maxWidth || 0xFFFF);
} else {
this.Text__drawTextLine(ctx, text, y);
}
};
window.GradientText = createjs.promote(GradientText, "Text");
}());
</script>
Now just create an instance of GradientText like this:
var text = new GradientText("Hello world!", "20px Arial", "#ff0000");
text.gradient = true;
You should see a gradient over text when you add it to the stage. Here is the jsfiddle for it: https://jsfiddle.net/r94zmwxa/
P.S. I've just written an example (black and white), but you can change the addColorStop from the this.gradient to set the gradient colors dynamically!

There is currently no way to do this. Sorry. There are plans to add better control on fill and stroke methods for Text in the future.

Related

openseadragon get selection dataurl/blob

I retrieve a rect from openSeadragonSelection:
viewer:
this.viewer = OpenSeadragon(this.config);
this.selection = this.viewer.selection({
showConfirmDenyButtons: true,
styleConfirmDenyButtons: true,
returnPixelCoordinates: true,
onSelection: rect => console.log(rect)
});
this.selection.enable();
rect by onSelection:
t.SelectionRect {x: 3502, y: 2265, width: 1122, height: 887, rotation:0, degrees: 0, …}
I have no idea how to get the canvas by rect from my viewer instance.
this.viewer.open(new OpenSeadragon.ImageTileSource(this.getTile(this.src)));
A self implemented imageViewer returned the canvas of the selected area. So I could get the blob and post it to the server:
onSave(canvas){
let source = canvas.toDataURL();
this.setState({source:source, crop: false, angle: 0});
save(this.dataURItoBlob(source), source.match(new RegExp("\/(.*);"))1]);
}
dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
How can I get the image of the viewer by rect. Rotation should be considered as well.
#iangilman:
Thank's alot for your advice. I created another canvas which I crop and after that put it back into the viewer. I was not sure if something similar was supported by your library yet:
const viewportRect = self.viewer.viewport.imageToViewportRectangle(rect);
const webRect = self.viewer.viewport.viewportToViewerElementRectangle(viewportRect);
const { x, y, width, height } = webRect || {};
const { canvas } = self.viewer.drawer;
let source = canvas.toDataURL();
const img = new Image();
img.onload = function () {
let croppedCanvas = document.createElement('canvas');
let ctx = croppedCanvas.getContext('2d');
croppedCanvas.width = width;
croppedCanvas.height = height;
ctx.drawImage(img, x, y, width, height, 0, 0, width, height);
let croppedSrc = croppedCanvas.toDataURL();
//update viewer with cropped image
self.tile = self.getTile(croppedSrc);
self.ImageTileSource = new OpenSeadragon.ImageTileSource(self.tile);
self.viewer.open(self.ImageTileSource);
}
img.src = source;
Rotation hasn't been considered yet.
I imagine you'll need to convert the rectangle into the proper coordinates, then create a second canvas and copy the appropriate bit out of the OSD canvas into the second one.
Looks like maybe the selection rectangle is in image coordinates? The OSD canvas will be in web coordinates, or maybe double that on an HDPI display. OSD has a number of conversion functions, for instance:
var viewportRect = viewer.viewport.imageToViewportRectangle(imageRect);
var webRect = viewer.viewport.viewportToViewerElementRectangle(viewportRect);
You can find out the pixel density via OpenSeadragon.pixelDensityRatio.
Once you have the appropriate rectangle it should be easy to copy out of the one canvas into another. I'm not sure how you incorporate rotation, but it might be as simple as adding a rotation call to one of the canvas contexts.
Sorry this is kind of vague, but I hope it helps!

change axis color dimple

I have a very simple line chart in dimple. I want to change the x and y axis colour to white.
var svg = dimple.newSvg(".line_chart_container", 400, 300),dataset;
var chart = new dimple.chart(svg, dataset);
var x = chart.addCategoryAxis("x", "Attempts");
//x.style ("fill","red")
var y = chart.addMeasureAxis("y", "Value");
y.showGridlines = true;
x.showGridlines = true;
var s = chart.addSeries(["Metric", "Value"], dimple.plot.bubble);
var lines = chart.addSeries("Metric", dimple.plot.line);
lines.lineWeight = 2;
lines.lineMarkers = true;
chart.assignColor("Metric", "#30D630");
chart.draw();
s.shapes.style("opacity", function (d) {
return (d.yValue === 0 ? 0 : 0.8);
});
I've checked dimple.axis documentation in GitHub but couldn't find any thing. There is a dimple.axis.colors attribute, but it changes the color of the data and not the axis. Does dimple even support this?
I've also tried to add style attribute(like in D3):
x.style ("fill","red")
but caught an error: Uncaught TypeError: x.style is not a function
Any idea?
x is not a d3 selection, it is a dimple.axis. You can access the inner d3 selection with the shapes property (which is standard for any dimple object). There is an example of that here.
Depending on if you want to change the line color, text color, or everything, you would do
x.shapes.selectAll("*").style("fill", "white")
where * could also be "text" or "line".
One note : the individual tick marks are <line> nodes, and to change their color you need to use 'stroke', not 'fill'.
Also, the actual axis line itself is not a <line> element, it's a <path> element. So to change that color would be :
x.shapes.select("path.dimple-custom-axis-line").style("stroke", "white");
You can also just manually write a css rule to override the style for a chart :
g.dimple-axis > g.tick > line, g.dimple-axis path.dimple-custom-axis-line {
stroke:white;
}
For X-axis
d3.selectAll("path.domain")[0][0].style.stroke = "red";
For Y-axis
d3.selectAll("path.domain")[0][1].style.stroke = "yellow";

Html Canvas add Text Or Image in Rendered Image

i am trying to add add text (water mark) in canvas generated image
here is my code.
html2canvas($("#frame"), {
onrendered: function (canvas) {
$("#outputImage").html(canvas);
}
what i should add in this code to add watermark mark in generated image
Inside the handler do the following:
html2canvas($("#frame"), {
onrendered: function (canvas) {
var ctx = canvas.getContext("2d"); // get 2D context of canvas
ctx.textBaseline = "top"; // start with drawing text from top
ctx.font = "20px sans-serif"; // set a font and size
ctx.fillStyle = "red"; // set a color for the text
ctx.fillText("WATERMARK", 20, 20); // draw the text at some position (x, y)
$("#outputImage").html(canvas);
}
}
There is also alignment modes using:
ctx.textAlign = "center"; // default: "start" = left-to-right/right-to-left
// depending on language, override with "left" or "right"
Check out Canvas.globalCompositeOperation. If you set it to the string 'lighter', it will lighten the pixels drawn by the next drawing command (such as fillText()). Here's a sample
<canvas id='canvas'></canvas>
<script>
var img = new Image();
img.src = 'http://www.javascripture.com/pic.jpg';
img.onload = function() {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0, canvas.width, canvas.height);
// Draw the Watermark
context.font = '48px sans-serif';
context.globalCompositeOperation = 'lighter';
context.fillStyle = '#444';
context.textAlign = 'center';
context.textBaseline = 'middle';
context.fillText('watermark', canvas.width / 2, canvas.height / 2);
};
</script>

KineticJS change color of text onclick

I am working on KineticJS(Latest version) and i have issue regarding change text color which drawn by drawFunc() shape object.
1)Here is the code of Shpae Object.
var sampleText = new Kinetic.Shape({
x:380,
y:700,
drawFunc: function(context) {
context.beginPath();
var x = 0;
var y = 0;
var text = 'Sample Text';
context.setAttr("font", '15pt Calibri');
context.setAttr('fillStyle','black');
context.fillText(text, x, y)
context.closePath();
// KineticJS specific context method
context.fillStrokeShape(this);
},
id:"sampleText"
});
2)I want to change color of "sample text" on click event which is written using core html5 code (context object).
colorTabViews.on('click', function (e) {
sampleText.sceneFunc(function(context) {
context.beginPath();
//how can i get text which already displayed in shape object("Sample text")?
//or to change color of "sample text"
context.setAttr('fillStyle','green');
context.closePath();
context.fillStrokeShape(this);
});
verticalText.draw();
});
But issue is ,it removes whole text nothing displayed instead of just changing "sample text" color.
Please advice either get text filled by context.fillText() function or alternate way that i can change text color on particular event.
Thanks for your time and consideration in advance.
-Naitik
To programatically change fillStyle inside a Kinetic.Shape
Attach a fill property to your shape object and reference your fill property inside the Kinetic.Shape:
var sampleText = new Kinetic.Shape({
x:10,
y:15,
sceneFunc: function(context) {
context.beginPath();
var x = 0;
var y = 0;
var text = 'Sample Text';
context.setAttr("font", '15pt Calibri');
context.setAttr('fillStyle',this.myFillStyle);
context.fillText(text, x, y)
context.closePath();
// KineticJS specific context method
context.fillStrokeShape(this);
},
id:"sampleText",
fill:"blue"
});
// add a property to sampleText that's used in its sceneFunc
sampleText.myFillStyle="black";
Then you can change that fill property in your click handler:
colorTabViews.on('click', function (e) {
sampleText.myFillStyle="red";
verticalText.draw();
});

WebGL single frame "screenshot" of webGL

tried searching for something like this, but I've had no luck. I'm trying to open a new tab with a screenshot of the current state of my webgl image. Basically, it's a 3d model, with the ability to change which objects are displayed, the color of those objects, and the background color. Currently, I am using the following:
var screenShot = window.open(renderer.domElement.toDataURL("image/png"), 'DNA_Screen');
This line succeeds in opening a new tab with a current image of my model, but does not display the current background color. It also does not properly display the tab name. Instead, the tab name is always "PNG 1024x768".
Is there a way to change my window.open such that the background color is shown? The proper tab name would be great as well, but the background color is my biggest concern.
If you open the window with no URL you can access it's entire DOM directly from the JavaScript that opened the window.
var w = window.open('', '');
You can then set or add anything you want
w.document.title = "DNA_screen";
w.document.body.style.backgroundColor = "red";
And add the screenshot
var img = new Image();
img.src = someCanvas.toDataURL();
w.document.body.appendChild(img);
Well it is much longer than your one liner but you can change the background color of the rectangle of the context.
printCanvas (renderer.domElement.toDataURL ("image/png"), width, height,
function (url) { window.open (url, '_blank'); });
// from THREEx.screenshot.js
function printCanvas (srcUrl, dstW, dstH, callback)
{
// to compute the width/height while keeping aspect
var cpuScaleAspect = function (maxW, maxH, curW, curH)
{
var ratio = curH / curW;
if (curW >= maxW && ratio <= 1)
{
curW = maxW;
curH = maxW * ratio;
}
else if (curH >= maxH)
{
curH = maxH;
curW = maxH / ratio;
}
return { width: curW, height: curH };
}
// callback once the image is loaded
var onLoad = function ()
{
// init the canvas
var canvas = document.createElement ('canvas');
canvas.width = dstW;
canvas.height = dstH;
var context = canvas.getContext ('2d');
context.fillStyle = "black";
context.fillRect (0, 0, canvas.width, canvas.height);
// scale the image while preserving the aspect
var scaled = cpuScaleAspect (canvas.width, canvas.height, image.width, image.height);
// actually draw the image on canvas
var offsetX = (canvas.width - scaled.width ) / 2;
var offsetY = (canvas.height - scaled.height) / 2;
context.drawImage (image, offsetX, offsetY, scaled.width, scaled.height);
// notify the url to the caller
callback && callback (canvas.toDataURL ("image/png")); // dump the canvas to an URL
}
// Create new Image object
var image = new Image();
image.onload = onLoad;
image.src = srcUrl;
}

Resources