How to store result of drag and drop as a image - javascript

I want to take the screenshot of the result of drag and drop, but I don't know how to do.
Actually, I found 2 javascript and using HTML5 such as html2canvas and canvas2image.
I am now combining them together, but it's still meet some problem with the canvas2image.
Please help me solve this problem if you have same experience, thank you a lot.
Please help me, I've been stock here for days.
Drag and drop code.
<script>
$(function() {
$( "#draggable" ).draggable();
$( "#draggable2" ).draggable();
$( "#droppable" ).droppable({
hoverClass: "ui-state-active",
drop: function( event, ui ) {
$( this )
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
}
});
});
</script>
Image generation code
<script>
window.onload = function() {
function convertCanvas(strType) {
if (strType == "JPEG")
var oImg = Canvas2Image.saveAsJPEG(oCanvas, true);
if (!oImg) {
alert("Sorry, this browser is not capable of saving " + strType + " files!");
return false;
}
oImg.id = "canvasimage";
oImg.style.border = oCanvas.style.border;
oCanvas.parentNode.replaceChild(oImg, oCanvas);
}
function convertHtml(strType) {
$('body').html2canvas();
var queue = html2canvas.Parse();
var canvas = html2canvas.Renderer(queue,{elements:{length:1}});
var img = canvas.toDataURL();
convertCanvas(strType);
window.open(img);
}
document.getElementById("html2canvasbtn").onclick = function() {
convertHtml("JPEG");
}
}
</script>
HTML code
<body>
<h3>Picture:</h3>
<div id="draggable">
<img src='http://1.gravatar.com/avatar/1ea64135b09e00ab80fa7596fafbd340? s=50&d=identicon&r=R'>
</div>
<div id="draggable2">
<img src='http://0.gravatar.com/avatar/2647a7d4b4a7052d66d524701432273b?s=50&d=identicon&r=G'>
</div>
<div id="dCanvas">
<canvas id="droppable" width="500" height="500" style="border: 2px solid gray" class="ui-widget-header" />
</div>
<input type="button" id="bGenImage" value="Generate Image" />
<div id="dOutput"></div>
</body>

A working example, without libraries:
<html>
<head>
<script>
function allowDrop(e)
{
e.preventDefault();
}
function drag(e)
{
//store the position of the mouse relativly to the image position
e.dataTransfer.setData("mouse_position_x",e.clientX - e.target.offsetLeft );
e.dataTransfer.setData("mouse_position_y",e.clientY - e.target.offsetTop );
e.dataTransfer.setData("image_id",e.target.id);
}
function drop(e)
{
e.preventDefault();
var image = document.getElementById( e.dataTransfer.getData("image_id") );
var mouse_position_x = e.dataTransfer.getData("mouse_position_x");
var mouse_position_y = e.dataTransfer.getData("mouse_position_y");
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// the image is drawn on the canvas at the position of the mouse when we lifted the mouse button
ctx.drawImage( image , e.clientX - canvas.offsetLeft - mouse_position_x , e.clientY - canvas.offsetTop - mouse_position_y );
}
function convertCanvasToImage() {
var canvas = document.getElementById('canvas');
var image_src = canvas.toDataURL("image/png");
window.open(image_src);
}
</script>
</head>
<body>
<div style="float:left" >
<div>
<img id="img1" draggable="true" ondragstart="drag(event)" src='img1.png'>
<img id="img2" draggable="true" ondragstart="drag(event)" src='img2.png'>
<input type="button" onclick="convertCanvasToImage()" value="Generate Image" style="float:right"/>
</div>
<canvas id="canvas" ondrop="drop(event)" ondragover="allowDrop(event)" width="500" height="500" style="border: 1px solid gray" />
</div>
</body>
The images must have the same origin in order to use toDataURL.
The resulting image is open on a new window, as in your code, but you can also, append it on the page, save on the disk or upload it on a server.
http://fiddle.jshell.net/gael/GF96n/4/

Related

Removing 'white-space' of hidden images

I have a list of images that I would like to hide/show based on which <li> element is clicked. I have been able to do this successfully, however, there is still the white space below/above the image that is showing. Here is the code I am currently using:
HTML
<div class="img-container">
<img id="img1" src="img/image1.jpg" />
<img id="img2" src="img/image2.jpg" />
<img id="img3" src="img/image3.jpg" />
</div>
CSS
.img-container{
text-align: center;
visibility: hidden;
margin-top: 20px;
}
JS
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
var img3 = document.getElementById('img3');
("li:nth-child(2)").on('click', function() {
img1.style.visibility = 'visible';
img2.style.visibility = 'hidden';
img3.style.visibility = 'hidden';
});
("li:nth-child(3)").on('click', function(){
img2.style.visibility = 'visible';
img1.style.visibility = 'hidden';
img3.style.visibility = 'hidden';
});
("li:last-child").on('click', function() {
img3.style.visibility = 'visible';
img2.style.visibility = 'hidden';
img1.style.visibility = 'hidden';
});
I have tried playing around with the display: hidden css property paired with .toggle() but cannot seem to quite get it working correctly. I have tried searching for this but cannot find anything on removing the white space the hidden image is holding. Am relatively new to JS/jQuery. Thanks.
You could use the css property display and values none and block.
The display property specifies if/how an element is displayed.
replace for visible img:
img1.style.visibility = 'visible';
for:
$("#img1").css("display", "block");
And replace for invisible img:
img1.style.visibility = 'hidden';
for:
$("#img1").css("display", "none");
Could use more useful inline-block instead block for lists.
If looking for jQuery solution:
var $img1 = $( "#img1" ),
$img2 = $( "#img2" ),
$img3 = $( "#img3" );
$( "li:nth-child(2)" ).on( "click", function() {
$img1.show();
$img2.hide();
$img3.hide();
} );
$( "li:nth-child(3)" ).on( "click", function() {
$img1.hide();
$img2.show();
$img3.hide();
} );
$( "li:nth-child(4)" ).on( "click", function() {
$img1.hide();
$img2.hide();
$img3.show();
} );
$( "li:last-child" ).on( "click", function() {
$img1.show();
$img2.show();
$img3.show();
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul style="list-style: none;">
<li>Click a button:</li>
<li><button>Show First Photo</button></li>
<li><button>Show Second Photo</button></li>
<li><button>Show Thrid Photo</button></li>
<li><button>Reset</button></li>
</ul>
<div class="img-container">
<img id="img1" width="300" height="300" src="https://blognumbers.files.wordpress.com/2010/09/1.jpg" />
<img id="img2" width="300" height="300" src="https://blognumbers.files.wordpress.com/2010/09/2.jpg" />
<img id="img3" width="300" height="300" src="https://blognumbers.files.wordpress.com/2010/09/3.jpg" />
</div>
When visibility is set to hidden, the element is not shown but still takes up space on the page.
When display is set to none, the element is neither shown nor does it take up any space on the page.
More often, I usually need:
display = 'none';
or
display = ''; // to have it show
In addition to using display instead of visibility you could also consider making your JS a little easier to handle. You could simply show the img which has the same index as that of the clicked li.
EG:
$(function() {
$(".img-controller li").on("click", function() {
var i = $(this).index();
$(".img-container img").hide();
$(".img-container img:eq(" + i + ")").show();
});
$(".img-container img").not(":first").hide();
});
.img-controller {
list-style-type: none;
padding: 0;
}
.img-controller li {
display: inline-block;
background: #eee;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="img-controller">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<div class="img-container">
<img src="https://placekitten.com/50/50" />
<img src="https://placekitten.com/50/40" />
<img src="https://placekitten.com/50/30" />
</div>

Drag images over canvas and save png

I'm creating an application with the image of a christmas tree that is placed in a canvas element , where there is the possibility of drag images over it . After the tree is decorated with the draggable images, the user has to be able to save the entire composition (canvas + images) as a PNG file . The problem is: when I drag the images to the canvas, they are hidden behind the christmas tree. Can you please help me to fix it?
Here's the code:
<html>
<head>
<script>
function allowDrop(e)
{
e.preventDefault();
}
function drag(e)
{
//store the position of the mouse relativly to the image position
e.dataTransfer.setData("mouse_position_x",e.clientX - e.target.offsetLeft );
e.dataTransfer.setData("mouse_position_y",e.clientY - e.target.offsetTop );
e.dataTransfer.setData("image_id",e.target.id);
}
function drop(e)
{
e.preventDefault();
var image = document.getElementById( e.dataTransfer.getData("image_id") );
var mouse_position_x = e.dataTransfer.getData("mouse_position_x");
var mouse_position_y = e.dataTransfer.getData("mouse_position_y");
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var imageObj=new Image();
imageObj.onload=function(){
ctx.save();
ctx.drawImage(this,0,0,canvas.width,canvas.height);
ctx.restore();
}
imageObj.src="bg.png";
// the image is drawn on the canvas at the position of the mouse when we lifted the mouse button
ctx.drawImage( image , e.clientX - canvas.offsetLeft - mouse_position_x , e.clientY - canvas.offsetTop - mouse_position_y );
}
function convertCanvasToImage() {
var canvas = document.getElementById('canvas');
var image_src = canvas.toDataURL("image/png");
window.open(image_src);
}
</script>
<style type="text/css">
body {
text-align: center;
}
#wrapper {
text-align: left;
width: 870px;
height:566px;
margin-left: auto;
margin-right: auto;
}
#options{
width: 70px;
height:566px;
float:left;
}
#options img {
margin-bottom: 15px;
}
#canvas{
width:800px;
height:566px;
float:left;
background-image:url(../images/bg.png);
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="options">
<img id="img1" draggable="true" ondragstart="drag(event)" src='estrela.png'>
<img id="img2" draggable="true" ondragstart="drag(event)" src='bola.png'>
<img id="img3" draggable="true" ondragstart="drag(event)" src='sino.png'>
<img id="img4" draggable="true" ondragstart="drag(event)" src='bota.png'>
<img id="img5" draggable="true" ondragstart="drag(event)" src='anjo.png'>
<img id="img6" draggable="true" ondragstart="drag(event)" src='laco.png'>
</div>
<canvas id="canvas" onDrop="drop(event)" onDragOver="allowDrop(event)" width="800" height="566"></canvas>
<input type="button" onClick="convertCanvasToImage()" value="Gerar Imagem" style="float:right"/>
</body>
Thanks!
Check out this post which allows you to drag images from a toolbar and drop them on the canvas:
HTML5 drag and drop images from a toolbar to a canvas
When you're done creating your tree, you can save the canvas as an image by converting it to an image and displaying the image in a new browser tab. The user can then right-click-save that image to their local drive:
$("#save").click(function(){
var html="<p>Right-click on image below and Save-Picture-As</p>";
html+="<img src='"+canvas.toDataURL()+"' alt='image from canvas'/>";
var tab=window.open();
tab.document.write(html);
});
Some browsers (Chrome, Firefox) even allow the user to right-click the canvas element itself and save it as an image.

How do I get one jquery alert at the end of the game?

This code is for a drag and drop game. Currently, the alert("correct") comes up after each different piece is dragged to its target. How do I change this so that the alert only comes up once at the end of the game, saying how many were correct?
the html:
<img class="drag-me" id="drag1" src="images/drag1.png">
<img class="drag-me" id="drag2" src="images/drag2.png">
<img class="drag-me" id="drag3" src="images/drag3.png">
<img class="drag-me" id="drag4" src="images/drag4.png">
<img class="target" id="target1" src="images/target1.png">
<img class="target" id="target2" src="images/target2.png">
<img class="target" id="target3" src="images/target3.png">
<img class="target" id="target4" src="images/target4.png">
the jquery:
$('.drag-me').draggable({revert:"invalid", snap:".target"});
$('.target').droppable({
drop: function( event, ui ) {
itemsInPosition++;
// get id of draggable and droppable id
var draggableID = $(ui.draggable).attr("id");
var droppableID = $(this).attr("id");
if(draggableID[4]==droppableID[6]){
alert("correct")
testIfComplete();
totalCorrect++;
}
}
});
var itemsInPosition = 0;
var totalItems = 4;
var totalCorrect = 0;
function testIfComplete(){
if(itemsInPosition==totalItems){
alert("You got " + totalCorrect + " right")
}
}
Thanks !
May be , you should choose the suitable libraries: JS+CSS for jquery UI.
See this fiddle . it works.
http://jsfiddle.net/abdennour/67SrS/
var itemsInPosition = 0;
var totalItems = 4;
var totalCorrect = 0;
$('.drag-me').draggable({revert:"invalid", snap:".target"});
$('.target').droppable({
drop: function( event, ui ) {
itemsInPosition++;
// get id of draggable and droppable id
var draggableID = $(ui.draggable).attr("id");
var droppableID = $(this).attr("id");
if(draggableID[4]==droppableID[6]){
alert("correct")
testIfComplete();
totalCorrect++;
}
}
});
and you can conclude& download the suitables libraries from this fiddle :
http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/overcast/jquery-ui.css

Drag and Drop to HTML5 Canvas

I'm dragging an html element and dropped to a canvas, took the location where released and plot the object at same location at canvas. But showing at the different location. See my code.
Script
function init() {
var canvas = document.getElementById("graphCanvas");
var context = canvas.getContext("2d");
context.lineWidth = 2;
}
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text",ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
document.getElementById("graphCanvas").getContext("2d").drawImage(document.getElementById(data),
ev.clientX, ev.clientY);
}
HTML
<body onload="init();">
<canvas id="graphCanvas" ondrop="drop(event)" ondragover="allowDrop(event)" height=300 width=300 style="border:1px solid #000000;"></canvas>
<img id="img1" src="http://static.tumblr.com/vcbmwcj/foumiteqs/arrow_up_alt1.svg" draggable="true" ondragstart="drag(event)"/>
</body>
Fixed. Updated code is http://jsfiddle.net/YXxsH/5/. Calculations are done with pageX and pageY and image offset values.

How do I toggle an iframe to maximize or minimize in javascript?

I'm using Prototype here and would like to build a simple toggler that toggles an iframe which contains the page the toggler is on to maximize to the browsers full size or minimize to its original size. Any ideas?
This works for me in IE7 & FF3.6 (only available at work).
function getDocWidth() {
var D = document;
return Math.max(
Math.max(D.body.scrollWidth, D.documentElement.scrollWidth),
Math.max(D.body.offsetWidth, D.documentElement.offsetWidth),
Math.max(D.body.clientWidth, D.documentElement.clientWidth)
);
}
function getDocHeight() {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
}
var isFullScreen = false;
var orgDimensions = new Array();
function toggleFullScreen() {
ifr = document.getElementById("iFrameWin");
if (!isFullScreen) {
orgDimensions[0] = ifr.style.width;
orgDimensions[1] = ifr.style.height;
ifr.style.width = getDocWidth() + "px";
ifr.style.height = getDocHeight() + "px";
}
else {
ifr.style.width = orgDimensions[0];
ifr.style.height = orgDimensions[1];
}
isFullScreen = !isFullScreen;
}
Where th iframe is:
<iframe id="iFrameWin" src="http://www.google.se" width="400" height="300"/>
This ofcourse needs for you to set the padding and margin to the containing page to 0 in wich case you would need to toggle from inside the iframe, calling parent.toggleFullScreen() I think.
Hope it was what you were looking for!
P.S
kudos to James Padolsey for the getDocHeight() function
**//here is the script**
<script src="Scripts/Jquery.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(function ($) {
$('#min1').click(function () {
var iframeheight = $('#iframe1').width();
if (iframeheight == 934) {
$('#iframe1').width(462);
document.getElementById('divFrame2').style.display = "block";
}
});
$('#max1').click(function () {
var iframeheight = $('#iframe1').width();
if (iframeheight == 462) {
$('#iframe1').width(934);
document.getElementById('divFrame2').style.display = "none";
}
});
$('#min2').click(function () {
var iframeheight = $('#iframe2').width();
if (iframeheight == 934) {
$('#iframe2').width(462);
document.getElementById('divFrame1').style.display = "block";
}
});
$('#max2').click(function () {
var iframeheight = $('#iframe2').width();
if (iframeheight == 462) {
$('#iframe2').width(934);
document.getElementById('divFrame1').style.display = "none";
}
});
});
</script>
**//style**
<style type="text/css">
.bdr
{
border: 1px solid #6593cf;
}
</style>
**//aspx sample**
<form id="form1" runat="server">
<table><tr><td >
<div id="divFrame1" class="bdr">
<div>
<img id="min1" src="Images/Minimize.jpg" width="13" height="14" border="0" alt="" />
<img id="max1" src="Images/Maximize.jpg" name="Image6" width="13" height="14" border="0"
id="Image6" alt="" />
</div>
<iframe name="content" id="iframe1" src="http://www.dynamicdrive.com/forums/archive/index.php/t-2529.html"
frameborder="0" height="321" width="462"></iframe>
</div>
</td ><td >
<div id="divFrame2" class="bdr">
<div>
<img id="min2" src="Images/Minimize.jpg" width="13" height="14" border="0" alt="" />
<img id="max2" src="Images/Maximize.jpg" name="Image6" width="13" height="14" border="0"
id="Image7" alt="">
</div>
<iframe name="content" id="iframe2" src="http://www.w3schools.com/default.asp" frameborder="0"
height="321" width="462"></iframe>
</div>
</td></tr></table>
</form>

Categories