Dynamically generated favicon - javascript

Would it be possible using only JavaScript and HTML to dynamically generate a favicon, using the current page's favicon as a background, and a random number in the foreground?
For example, lets say the current favicon looks similar to this:
======================
====XXXXXXXXXXXXXX====
====X=================
====X=================
====X=====XXXXXXXX====
====X============X====
====X============X====
====XXXXXXXXXXXXXX====
======================
If possible, how would I get it to look something similar to this using only JavaScript and HTML:
======================
====XXXXXXXXXXXXXX====
====X=================
====X=================
====X=====XXXXXXXX====
====X=========--111--=
====X=========--1-1--=
====XXXXXXXXXX----1--=
==============--1111-=
map:
= : white background
x : Original Favicon image
- : Red generated image with a number
1 : White text
Ideas:
Canvas?
Data Uri's?

EDIT: Got it working with
var canvas = document.createElement('canvas');
canvas.width = 16;canvas.height = 16;
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = '/favicon.ico';
img.onload = function() {
ctx.drawImage(img, 0, 0);
ctx.fillStyle = "#F00";
ctx.fillRect(10, 7, 6, 8);
ctx.fillStyle = '#FFFFFF';
ctx.font = 'bold 10px sans-serif';
ctx.fillText('2', 10, 14);
var link = document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.href = canvas.toDataURL("image/x-icon");
document.getElementsByTagName('head')[0].appendChild(link);
}
You can actually run chrome and paste this:
javascript: var canvas = document.createElement('canvas');canvas.width = 16;canvas.height = 16;var ctx = canvas.getContext('2d');var img = new Image();img.src = '/favicon.ico';img.onload = function() {ctx.drawImage(img, 0, 0);ctx.fillStyle = "#F00";ctx.fillRect(10, 7, 6, 8);ctx.fillStyle = '#FFFFFF';ctx.font = 'bold 10px sans-serif';ctx.fillText('2', 10, 14);var link = document.createElement('link');link.type = 'image/x-icon';link.rel = 'shortcut icon';link.href = canvas.toDataURL("image/x-icon");document.getElementsByTagName('head')[0].appendChild(link);}
into the browser and see it in action.

You might take a look at this question, which discusses how to change the favicon dynamically. Also here is a site that claims to play a game in the favicon using only JavaScript, canvas, and the data URI, which should work in all modern browsers except IE. Not sure if that would fulfill your requirements or not, but you can try reverse engineering how it works.
Here's an SO answer that explains how to use the canvas element to read the favicon data and get the image data out, which then can be modified and composed into a new icon.

I don't know about doing it all in the browser, but it would be easy to have a server endpoint that accepted parameters in the URL and returned a composed favicon. Then Javascript could modify the favicon url to get the image it wanted.

favicon.js does exactly this. This library can display a counter in the bottom right corner of the favicon, among other features.

Related

how to take a screenshot of piece of a webpage with phantomjs?

I understand how to take screenshot of entire webpage but how about capturing the view of an specific element using phantomjs.
I'm trying as follow
var page = require('webpage').create();
page.content = page.open('https://www.google.co.in/');
page.evaluate(function() {
var canvas = document.getElementById('hplogo');
var ctx = canvas.getContext('2d');
var img = new Image();
var imgdata = document.querySelectorAll('img');
img.src = imgdata[0].src;
var pattern = ctx.createPattern(img, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, 300, 300);
});
page.render('canvas.png');
phantom.exit();
Above code is not working, What 'm doing in above code is selecting the element of Google webpage img section though id then create an object of image and assign the src of query selected tag IMG and then fill the pattern, my hours of hard work did not yield any result.
WHAT I WANT: I want the screenshot of an img element rendered through 'page.open' which can be selected by query selector and output the png file. OTHER ALTERNATIVES OF PHANTOMJS ARE WELCOME.
Thanks in advance..

downloading images of two different d3 graphs in single html page?

I created an html page for my tool which works offline(client side). This page is creating two different d3 based graph and I created two different buttons (save and save1)for each graph to downlaod images of these. These two image download button works fine, when tested separately in two different html pages.
Now, Problem in combined html page, is that each button is downloading the image of first d3 based graph only.
I defined two different svg variable (svg and svg1) for each graph creation but i donot know how to call it differently in downloadimage script.
**I think there is problem while calling "node( ).parentNode.innerHTML;" (mentioned in following svg downlaod script)?
But I don't know how to call different SVG in this script.
This is my first time, I am working on d3.
**
d3.select("#save1").on("click", function(){ //button save in first graph;
var html1 = d3.select("svg") //var html in first graph;
.attr("version", 1.1)
.attr("xmlns", "http://www.w3.org/2000/svg")
.node( ).parentNode.innerHTML;
//console.log(html);
var imgsrc = 'data:image/svg+xml;base64,'+ btoa(html1);
var image = new Image;
image.src = imgsrc;
image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.fillStyle = "#FFFFFF";
context.fillRect(0,0,image.width,image.height);
context.drawImage(image, 0, 0);
var a = document.createElement('a');
a.download = "image.png";
a.href = canvas.toDataURL('image/png');
document.body.appendChild(a);
a.click();
}
});
This line:
var html1 = d3.select("svg")
Is always selecting the first SVG in the DOM, regardless the button you click.
Instead of that, give your SVGs unique IDs (like svg1 and svg2), and select by those IDs:
var html1 = d3.select("#svg1")
var html2 = d3.select("#svg2")

add download function to a click event with Javascript

I am wondering if it is possible to add a download function to a click event purely in Javascript, for example, when a user clicks on an image, it gets automatically downloaded. For example I have an image tag <img src="filelocation" id="img"/> and want it to be downloaded on click. (I can't use "download="myfile.png".
Is there something like
$('#img').on('click',function(e){
img.download="myfile.png";
});
All the answers online suggest adding the download="..." into my tag
Thanks!
Maybe something like this:
document.getElementById('download').click();
<a id="download" href="https://assets.entrepreneur.com/content/16x9/822/20150721193719-solshero3.jpeg" download hidden></a>
Play with it: here
But if you really can't have the download attribute: Play this then.
Good luck!!
You can create a anchor element on click of the image and use .click() to trigger the click on that anchor even if its not attach to your page.
And if this still violate the requirement, then you may have to achieve it with server-side works.
See Change name of download in javascript
window.onload = function() {
// Fake image for testment
var canvas = document.createElement('canvas');
canvas.width = 300;
canvas.height = 200;
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, 200, 100);
ctx.fillStyle = 'cyan';
ctx.fillText('test', 50, 50);
var makeImageDownloadable = function(image, name) {
image.addEventListener('click', function() {
var a = document.createElement('a');
a.href = image.src;
// may need to check the datatype, or just write image to another tmp canvas first.
a.download = name + '.png';
a.click();
});
};
var image = new Image();
image.onload = function() {
document.querySelector('#holder').appendChild(image);
makeImageDownloadable(image, 'testimage');
};
image.src = canvas.toDataURL('image/png');
};
<div id="holder"></div>
You can use the HTML5 download attribute.
<a href="http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg" download="my_download.png"><img src="http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg">
</a>
I am unsure of browser compatibility in this,better soultion would be to include server side scripts too.
JSFiddle: http://jsfiddle.net/k2rear94/
if u want this to be dynamic, try this.
$("SomeElement").onclick = function(){
$("<a id='tmp' href='link' download ></a>).appendTo("body");
$("#tmp").click();
$("#tmp").remove();
}
But remember, download attribute is not supported in IE.

HTML5 Canvas Tooltips

I am using the HTML5 Canvas. I have added images (BitmapImages) to the canvas and I now want to add simple tooltips to these bitmap images.
Is this possible ??? If so can someone tell / show me how I could achieve this ?
I am not sure if it makes a difference , but I am also using the Easel JS Framework ...
Here is an example of what I currently have:
var container = new Container(); // EaselJS Container
container.x = 100;
container.y = 100;
stage.addChild(container);
var image = new Image();
image.src = "image.png";
var bitmap = new Bitmap(image);
bitmap.x = 5;
bitmap.y = 5;
bitmap.mouseEnabled = true;
container.addChild(bitmap);
...
I have not tested this code, but basically a bitmap image is created and added to my stage. I now want to add a simple tool tip to my bitmap image, but cant seem to work out how :(
Any help would be greatly appreciated.
Cheers,
Jon.
Here's how I would do it:
stage.enableMouseOver();
bitmap.onMouseOver = function(e) {
stage.canvas.title = 'put your tooltip text here';
}
bitmap.onMouseOut = function(e) {
stage.canvas.title = '';
}
This works by using tooltips already provided by the browser.

converting Div to Canvas options [duplicate]

It would be incredibly useful to be able to temporarily convert a regular element into a canvas. For example, say I have a styled div that I want to flip. I want to dynamically create a canvas, "render" the HTMLElement into the canvas, hide the original element and animate the canvas.
Can it be done?
There is a library that try to do what you say.
See this examples and get the code
http://hertzen.com/experiments/jsfeedback/
http://html2canvas.hertzen.com/
Reads the DOM, from the html and render it to a canvas, fail on some, but in general works.
Take a look at this tutorial on MDN: https://developer.mozilla.org/en/HTML/Canvas/Drawing_DOM_objects_into_a_canvas (archived)
Its key trick was:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
'<foreignObject width="100%" height="100%">' +
'<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +
'<em>I</em> like ' +
'<span style="color:white; text-shadow:0 0 2px blue;">' +
'cheese</span>' +
'</div>' +
'</foreignObject>' +
'</svg>';
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svg);
img.onload = function () {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
}
img.src = url;
That is, it used a temporary SVG image to include the HTML content as a "foreign element", then renders said SVG image into a canvas element. There are significant restrictions on what you can include in an SVG image in this way, however. (See the "Security" section for details — basically it's a lot more limited than an iframe or AJAX due to privacy and cross-domain concerns.)
Sorry, the browser won't render HTML into a canvas.
It would be a potential security risk if you could, as HTML can include content (in particular images and iframes) from third-party sites. If canvas could turn HTML content into an image and then you read the image data, you could potentially extract privileged content from other sites.
To get a canvas from HTML, you'd have to basically write your own HTML renderer from scratch using drawImage and fillText, which is a potentially huge task. There's one such attempt here but it's a bit dodgy and a long way from complete. (It even attempts to parse the HTML/CSS from scratch, which I think is crazy! It'd be easier to start from a real DOM node with styles applied, and read the styling using getComputedStyle and relative positions of parts of it using offsetTop et al.)
You can use dom-to-image library (I'm the maintainer).
Here's how you could approach your problem:
var parent = document.getElementById('my-node-parent');
var node = document.getElementById('my-node');
var canvas = document.createElement('canvas');
canvas.width = node.scrollWidth;
canvas.height = node.scrollHeight;
domtoimage.toPng(node).then(function (pngDataUrl) {
var img = new Image();
img.onload = function () {
var context = canvas.getContext('2d');
context.translate(canvas.width, 0);
context.scale(-1, 1);
context.drawImage(img, 0, 0);
parent.removeChild(node);
parent.appendChild(canvas);
};
img.src = pngDataUrl;
});
And here is jsfiddle
Building on top of the Mozdev post that natevw references I've started a small project to render HTML to canvas in Firefox, Chrome & Safari. So for example you can simply do:
rasterizeHTML.drawHTML('<span class="color: green">This is HTML</span>'
+ '<img src="local_img.png"/>', canvas);
Source code and a more extensive example is here.
No such thing, sorry.
Though the spec states:
A future version of the 2D context API may provide a way to render fragments of documents, rendered using CSS, straight to the canvas.
Which may be as close as you'll get.
A lot of people want a ctx.drawArbitraryHTML/Element kind of deal but there's nothing built in like that.
The only exception is Mozilla's exclusive drawWindow, which draws a snapshot of the contents of a DOM window into the canvas. This feature is only available for code running with Chrome ("local only") privileges. It is not allowed in normal HTML pages. So you can use it for writing FireFox extensions like this one does but that's it.
You could spare yourself the transformations, you could use CSS3 Transitions to flip <div>'s and <ol>'s and any HTML tag you want. Here are some demos with source code explain to see and learn: http://www.webdesignerwall.com/trends/47-amazing-css3-animation-demos/
the next code can be used in 2 modes, mode 1 save the html code to a image, mode 2 save the html code to a canvas.
this code work with the library: https://github.com/tsayen/dom-to-image
*the "id_div" is the id of the element html that you want to transform.
**the "canvas_out" is the id of the div that will contain the canvas
so try this code.
:
function Guardardiv(id_div){
var mode = 2 // default 1 (save to image), mode 2 = save to canvas
console.log("Process start");
var node = document.getElementById(id_div);
// get the div that will contain the canvas
var canvas_out = document.getElementById('canvas_out');
var canvas = document.createElement('canvas');
canvas.width = node.scrollWidth;
canvas.height = node.scrollHeight;
domtoimage.toPng(node).then(function (pngDataUrl) {
var img = new Image();
img.onload = function () {
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
};
if (mode == 1){ // save to image
downloadURI(pngDataUrl, "salida.png");
}else if (mode == 2){ // save to canvas
img.src = pngDataUrl;
canvas_out.appendChild(img);
}
console.log("Process finish");
});
}
so, if you want to save to image just add this function:
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
}
Example of use:
<html>
<head>
</script src="/dom-to-image.js"></script>
</head>
<body>
<div id="container">
All content that want to transform
</div>
<button onclick="Guardardiv('container');">Convert<button>
<!-- if use mode 2 -->
<div id="canvas_out"></div>
</html>
Comment if that work.
Comenten si les sirvio :)
The easiest solution to animate the DOM elements is using CSS transitions/animations but I think you already know that and you try to use canvas to do stuff CSS doesn't let you to do. What about CSS custom filters? you can transform your elements in any imaginable way if you know how to write shaders. Some other link and don't forget to check the CSS filter lab.
Note: As you can probably imagine browser support is bad.
function convert() {
dom = document.getElementById('divname');
var script,
$this = this,
options = this.options,
runH2c = function(){
try {
var canvas = window.html2canvas([ document.getElementById('divname') ], {
onrendered: function( canvas ) {
window.open(canvas.toDataURL());
}
});
} catch( e ) {
$this.h2cDone = true;
log("Error in html2canvas: " + e.message);
}
};
if ( window.html2canvas === undefined && script === undefined ) {
} else {.
// html2canvas already loaded, just run it then
runH2c();
}
}

Categories

Resources