create canvas with js and align the element - html

I have this code below that helps me align the image to the center on any device/screen.
Now I need help with drawing the picture(myImage) as canvas and not $("body").append(img);
How can I do this?
<script>
$(document).ready(function() {
var img=new Image();
img.src="myImage.jpg"
img.onload=function() {
// console.log("image is loaded, yessss!")
function my_resize() {
var w=img.width;
var h=img.height;
var ww=$(window).width();
var wh=$(window).height();
var ox=(ww-w)/2;
var oy=(wh-h)/2;
console.log("data is "
+w+","+
+h+","+
+ww+","+
+wh+","+
+ox+","+
+oy+","
);
$(img).offset({left:ox,top:oy,});
}
$("body").append(img);
my_resize();
$(window).resize(function() {
my_resize();
});
}
});
</script>

Try this jsfiddle:
http://jsfiddle.net/MqkRs/4/

Related

Export Google visualization as picture

I'm trying to convert a wordtree Google visualization to an image. The current code below runs the wordtree so I can see the visual, but I can't figure out the last section to convert to an image or export as an image. (var my_div = section to end)
I have tried changing code from link below, but can't get it to save as an image.
https://developers.google.com/chart/interactive/docs/printing
I'm also doing this inside of jsfiddle.net to try and make this work.
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current'); // Don't need to specify chart libraries!
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
google.visualization.drawChart({
"containerId": "mywordtree",
"dataSourceUrl": "https://docs.google.com/spreadsheets/d/1vi-YzV7s7eZ25938Q57DbZvT0iqggiCqRvDgxeZtP6c/edit?usp=sharing",
"query":"SELECT A",
"chartType": "WordTree",
"options": {
wordtree: {
format: 'implicit',
//alt type is 'suffix', 'prefix'
type: 'suffix',
word: 'prescription'
}
}
});
}
var my_div = document.getElementById('chart_div');
var my_chart = new google.visualization.ChartType(mywordtree);
google.visualization.events.addListener(my_chart, 'ready', function () {
mywordtree.innerHTML = '<img src="' + my_chart.getImageURI() + '">';
});
my_chart.draw(data);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="mywordtree" style="width: 1000px; height: 1000px;"></div>
</body>
</html>
first, in order to generate an image of the chart,
you need to wait for the chart's 'ready' event.
in order to wait for the 'ready' event,
you need access to the chart object.
you will not be able to use the google.visualization.drawChart method,
because it does not return a handle to the chart.
next, the WordTree chart, does not have a method for getImageURI,
so you will need to create the image manually, from a blob.
see following working snippet...
google.charts.load('current').then(function () {
// get chart container
var container = document.getElementById('mywordtree');
// create chart
var chart = new google.visualization.ChartWrapper({
chartType: 'WordTree',
containerId: container.id,
dataSourceUrl: 'https://docs.google.com/spreadsheets/d/1vi-YzV7s7eZ25938Q57DbZvT0iqggiCqRvDgxeZtP6c/edit?usp=sharing',
options: {
wordtree: {
format: 'implicit',
//alt type is 'suffix', 'prefix'
type: 'suffix',
word: 'prescription'
}
}
});
// listen for ready event
google.visualization.events.addListener(chart, 'ready', function () {
var domUrl; // object url
var image; // chart image
var imageUrl; // chart image url
var svg; // svg element
// add svg namespace to chart
svg = container.getElementsByTagName('svg')[0];
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
// create image url from svg
domUrl = window.URL || window.webkitURL || window;
imageUrl = domUrl.createObjectURL(new Blob([svg.outerHTML], {type: 'image/svg+xml'}));
// create chart image
image = new Image();
image.onload = function() {
// replace chart with image
container.innerHTML = image.outerHTML;
}
image.src = imageUrl;
});
// draw chart
chart.draw();
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="mywordtree"></div>

Text is not appending on the canvas after crop by SVG

In the canvas i am using clipTo function to crop it.It works for circle,rectangle,....i could add whatever like text and images after that.I added the code below which works.
$(function(){
var canvas = new fabric.Canvas('Canvas',{backgroundColor: '#ffffff',preserveObjectStacking: true});
canvas.clipTo = function (ctx) {
ctx.arc(250, 300, 200, 0, Math.PI*2, true);
};
canvas.add(new fabric.IText('Welcome ', {
left : fabric.util.getRandomInt(120,120),
top:fabric.util.getRandomInt(400, 400)
}));
canvas.renderAll();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.18/fabric.js"></script>
<div class="container">
<div id='canvascontain' width='1140' height='600' style='left:0px;background-color:rgb(240,240,240)'>
<canvas id="Canvas" width='1140' height='600'></canvas>
</div>
After that i am trying to crop the canvas by SVG file.This also works.But problem is i could not add texts or images after clipTo by canvas.The below code is not adding the text to canvas.
fabric.loadSVGFromURL('https://s3-us-west-2.amazonaws.com/fabric-canvas/test.svg', function (objects, options) {
var shape = fabric.util.groupSVGElements(objects, options);
canvas.clipTo = function (ctx) {
shape.render(ctx);
};
canvas.renderAll();
});
canvastext = new fabric.IText('Hi to all',{
left : fabric.util.getRandomInt(120, 120),
top:fabric.util.getRandomInt(400, 400)
});
canvas.add(canvastext);
canvas.renderAll();
The canvas image is:
Thanks in advance.
I have found the solution.Instead of using loadSVGFromURL i am fetching the path from svg file and cropped the canvas like below.
HTML:
<div id='svgpath'>
<object data="test.svg" type="image/svg+xml"
id="svgpathd" width="100%" height="100%"></object>
</div>
Script:
canvas.clipTo = function (ctx) {
var a = document.getElementById("svgpathd");
a.addEventListener("load",function(){
var svgDoc = a.contentDocument;
var clippath = svgDoc.getElementsByTagName("clipPath")[0].getAttribute('id');
var path = svgDoc.getElementsByTagName("path");
for(i=0;i<path.length;i++){
if(svgDoc.getElementsByTagName("path")[i].getAttribute('clip-path')=="url(#"+clippath+")"){
pathd = svgDoc.getElementsByTagName("path")[i].getAttribute('d');
paths = pathd.replace(" L"," L");
localStorage.setItem('svgpathd', paths);
}
}
});
}
document.getElementById('svgpath').style.display='none';
svgpathd = localStorage.getItem('svgpathd');
//Path has been taken and clipping the canvas with the path values
ctx.beginPath();
var path = svgpathd.split("L");
var arr = [];
m = path[0].slice(1).split(" ");
ctx.moveTo(m[0],m[1]);
for(i=0;i<path.length;i++){
arr[i]=path[i].slice(0,-1).slice(1);
}
for(i=0;i<arr.length;i++){
p = arr[i].split(" ");
ctx.lineTo(p[0],p[1]);
}
ctx.fill();
ctx.closePath();
}

I want opacity one when object:over in fabric.js

canvas.on('object:over', function(e) {
//I want change opacity of object on mouse over on object
});
canvas.on('object:out', function(e) {
});
I want opacity one when object:over and otherwise opacity should be 0
If the context is 2d. Using context.globalAlpha will solve the case.
<script>
window.onload = function() {
var canvas=document.getElementById("drawing"); // grabs the canvas element
var context=canvas.getContext("2d"); // returns the 2d context object
canvas.on('object:over', function(e) {
//I want change opacity of object on mouse over on object
//blue rectangle
context.fillStyle= "#b0c2f7";
context.globalAlpha=0; // Half opacity
context.fillRect(10,10,100,50);
});
canvas.on('object:out', function(e) {
context.fillStyle= "#b0c2f7";
context.globalAlpha=1; // full opacity
context.fillRect(10,10,100,50);
});
}
</script>
I am export of fabric.js. But the canvas in fabric.js haven't object:over and object:out.
fabric.js have mouse:over, mouse:out, object:moving: doc address http://fabricjs.com/docs/fabric.Canvas.html
when mouse:over
canvas.on('mouse:over', function(e) {
var targetObj = e.target;
targetObj.setOpacity(0.5);
});
canvas.on('mouse:out', function(e) {
var targetObj = e.target;
targetObj.setOpacity(1);
});

move multiple images from one canvas to other canvas

There is an example given at http://www.rgraph.net/blog/2013/january/an-example-of-html5-canvas-drag-n-drop.html
I am not able to add multiple images into canvas 1 and move those added images to canvas 2. Also I should be able to drag(move the added image within canvas 2) those added images in second canvas.
function dragDrop(e, ui) {
// get the drop point (be sure to adjust for border)
var x = parseInt(ui.offset.left - offsetX) - 1;
var y = parseInt(ui.offset.top - offsetY);
// get the drop payload (here the payload is the $tools index)
var theIndex = ui.draggable.data("toolsIndex");
// drawImage at the drop point using the dropped image
ctx.drawImage($tools[theIndex], x, y, 32, 32);
}
http://jsfiddle.net/cyur7/
This jsfiddle link is working fine.
This solution uses the KineticJS library to accomplish your need.
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/bSpBF/
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.5.1.min.js"></script>
<style>
body{ background-color: ivory; padding:10px;}
#container1,#container2{
border:solid 1px #ccc;
margin-top: 10px;
width:300px;
height:100px;
}
#container2{
height:300px;
}
</style>
<script>
$(function(){
var highlightWidth=8;
var stage = new Kinetic.Stage({
container: 'container1',
width: 300,
height: 100
});
var layer = new Kinetic.Layer();
stage.add(layer);
var dropzone = new Kinetic.Stage({
container: 'container2',
width: 300,
height: 300
});
var dropLayer = new Kinetic.Layer();
dropzone.add(dropLayer);
// these must go after the creation of stages & layers
addBackground(stage,layer,dropLayer);
layer.draw();
addBackground(dropzone,dropLayer,layer);
dropLayer.draw();
// get images & then trigger start()
var images={};
var URLs = {
house1: 'https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-3.jpg',
house2: 'https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-4.jpg',
house3: 'https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-1.jpg'
};
loadImages(URLs,start);
function start(){
var house1=kImage(images.house1,10,10,50,50,layer);
var house2=kImage(images.house2,75,10,50,50,layer);
var house3=kImage(images.house3,140,10,50,50,layer);
layer.draw();
}
function swapStagesIfSelected(sourceLayer,destinationLayer,startX,startY){
// get all elements on the source layer
var elements=sourceLayer.get("Image");
// don't let dropped elements fall off the stage
var totalWidth=0;
var maxHeight=-999;
var layerWidth=destinationLayer.getStage().getWidth();
var layerHeight=destinationLayer.getStage().getHeight();
for(var i=0;i<elements.length;i++){
if(elements[i].isSelected){
totalWidth+=elements[i].getWidth();
maxHeight=Math.max(elements[i].getHeight(),maxHeight);
}
}
if(startX+totalWidth>layerWidth){
startX=layerWidth-totalWidth-15;
}
if(startY+maxHeight>layerHeight){
startY=layerHeight-maxHeight-15;
}
// move all selected images
// to the clicked x/y of the destination layer
for(var i=0;i<elements.length;i++){
var element=elements[i];
if(element.isSelected){
var img=element.getImage();
kImage(img,startX,startY,element.getWidth(),element.getHeight(),destinationLayer);
startX+=element.getWidth()+10;
element.remove();
}
}
sourceLayer.draw();
destinationLayer.draw();
}
// build the specified KineticJS Image and add it to the specified layer
function kImage(image,x,y,width,height,theLayer){
var image=new Kinetic.Image({
image:image,
x:x,
y:y,
width:width,
height:height,
strokeWidth:0.1,
stroke:"green",
draggable:true
});
image.myLayer=theLayer;
image.isSelected=false;
image.on("click",function(){
highlight(this);
this.myLayer.draw();
});
image.myLayer.add(image);
return(image);
}
// build a background image and add it to the specified stage
function addBackground(theStage,theLayer,otherLayer){
var background = new Kinetic.Rect({
x: 0,
y: 0,
width: theStage.getWidth(),
height: theStage.getHeight(),
fill: "white",
stroke: "green",
strokeWidth: 1
});
background.on("click",function(){
var pos=theStage.getMousePosition();
var mouseX=parseInt(pos.x);
var mouseY=parseInt(pos.y);
swapStagesIfSelected(otherLayer,theLayer,mouseX,mouseY);
});
theLayer.add(background);
}
///////////// Image loader
function loadImages(URLs, callback) {
var loaded = 0;
var needed = 0;
for(var url in URLs) { needed++; console.log(url); }
for(var url in URLs) {
images[url] = new Image();
images[url].onload = function() {
if(++loaded >= needed) {
callback(images);
}
};
images[url].src = URLs[url];
}
}
///////////// Toggle Highlighting
function highlight(element,setStrokeWidth){
if(setStrokeWidth){
element.setStrokeWidth(setStrokeWidth);
}else{
if(element.getStrokeWidth()>5){
element.setStrokeWidth(0.1);
element.isSelected=false;
}else{
element.setStrokeWidth(highlightWidth);
element.isSelected=true;
}
}
}
}); // end $(function(){});
</script>
</head>
<body>
<p>Click on image(s) to toggle selection</p>
<p>Then click in the other canvas to drop</p>
<div id="container1"></div>
<div id="container2"></div>
<button id="clear">Clear Hightlights</button>
<button id="swap">Swap Selected</button>
</body>
</html>

How to implement a Hover state for an Object

I have a code for a menu which is implemented for Click.
function DropDown(el) {
this.dd = el;
this.initEvents();
}
DropDown.prototype = {
initEvents : function() {
var obj = this;
var loc = window.location.pathname;
var filename = loc.match(/([^\/]+)(?=\.\w+$)/)[0];
console.log("sssss" + $(this).attr("id"));
obj.dd.on('click', function(event){
console.log($(this).attr("id"));
if(!($(this).hasClass("active")) && ( $(this).attr("id")) === filename) {
console.log("Hiding");
$(this).toggleClass('active');
event.stopPropagation();
}
});
}
}
$(function() {
var dd1 = new DropDown( $('#value') );
var dd2 = new DropDown( $('#diagnostics') );
var dd3 = new DropDown( $('#design') );
var dd4 = new DropDown( $('#delivery') );
//$('.wrapper-dropdown-5').on('click', function(e){ console.log(e); });
$(document).click(function() {
// all dropdowns
$('.wrapper-dropdown-5').removeClass('active');
});
});
If you see obj.dd.on('click', function(event){, that is where the click action is being intercepted. But I want to implement hover state, and to my surprise, it is not working, I tried using hover, mouseover and mouseout there, but nothing works. Only click is working.
Do you have any idea what might be the problem or how could I implement Hover in this scenario?
Thanks