Good day,
I try to draw all tiles, on cavas using leaflet.js as provider.
But, as it used translate3d transform
1 level - map Pane
2 level - overlay Pane(I also lokking for solution about SVG Pane. I use canVG to convert svg to canvas, but don't understand how to create canvas correctly)
How to draw tiles on canvas?
For example
1 level - transform: translate3d(-247px, 184px, 0px);
This is part of code:
var svgE = $(overlayPane).find('svg');
var xml;
var mapPane = $(".leaflet-map-pane")[0];
var mapTransform = mapPane.style.transform.split(",");
var mapX = parseFloat(mapTransform[0].split("(")[1].replace("px", ""));
var mapY = parseFloat(mapTransform[1].replace("px", ""));
var canvas = document.createElement("canvas");
canvas.className = "screenShotTempCanvas";
canvas.width = map.getSize().x;
canvas.height = map.getSize().y;
var ctx = canvas.getContext('2d');
$(canvas).insertBefore($(".leaflet-zoom-animated"));
if ($("img.leaflet-tile").length !== 0) {
var myTiles = $("img.leaflet-tile");
var tilesLeft = [];
var tilesTop = [];
var tileMethod = [];
for (var i = 0; i < myTiles.length; i++) {
if (myTiles[i].style.left != "") {
tilesLeft.push(parseFloat(myTiles[i].style.left.replace("px", "")));
tilesTop.push(parseFloat(myTiles[i].style.top.replace("px", "")));
tileMethod[i] = "left";
} else if (myTiles[i].style.transform != "") {
var tileTransform = myTiles[i].style.transform.split(",");
tilesLeft[i] = parseFloat(tileTransform[0].split("(")[1].replace("px", ""));
tilesTop[i] = parseFloat(tileTransform[1].replace("px", ""));
myTiles[i].style.transform = "";
tileMethod[i] = "transform";
} else {
tilesLeft[i] = 0;
tilesRight[i] = 0;
tileMethod[i] = "neither";
};
myTiles[i].setAttribute('crossOrigin', 'anonymous');
myTiles[i].style.left = (tilesLeft[i]) + "px";
myTiles[i].style.top = (tilesTop[i]) + "px";
ctx.drawImage(myTiles[i], tilesLeft[i], tilesTop[i])
};
}
setTimeout(function() {
var myImage = canvas.toDataURL("image/jpeg");
var link = document.createElement('a');
link.download = "test.jpeg";
link.href = myImage;
document.body.appendChild(link);
$(link).css("display", "none");
link.click();
document.body.removeChild(link);
console.log(sdfsdfgsdfg)
}, 10000)
Second question how to correctly create canvas for SVG?
if ($(map.getContainer()).find('svg').length !== undefined && $(map.getContainer()).find('svg').length !== 0) {
svgE.each(function() {
L.DomUtil.getPosition(svgE);
xml = new XMLSerializer().serializeToString(this);
canvg(canvas, xml);
$(canvas).insertBefore(this);
$(this).attr('class', 'tempHide').attr("id", "TempSvgToHide").hide();
});
}
Related
based on this question
How to use LUT with JavaScript?
I tried to use this code
http://jsfiddle.net/gxu080ve/1/
var img = new Image,
canvas = document.getElementById("myCanvas"),
ctx = canvas.getContext("2d"),
src = "http://i.imgur.com/0vcCTK9.jpg?1"; // insert image url here
img.crossOrigin = "Anonymous";
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage( img, 0, 0 );
// alternateImage(img, canvas, ctx);
localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") );
loadNew();
}
img.src = src;
// make sure the load event fires for cached images too
if ( img.complete || img.complete === undefined ) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
var imgLut = new Image,
canvasLut = document.getElementById("myCanvasLut"),
ctxLut = canvasLut.getContext("2d"),
srcLut = "https://gm1.ggpht.com/nX2ZUYrMwPSXu5zGeeoMKyZP_R4nE205ivAdc3_yaccMEy8QYInfY_ynUB-NmrjvPKn0i1k7bdtHyk3Ul99ndvjvoCASud8FdIdq1fRrqDOCGK01rXgZZQ34ATKvtrkoysUCBmTUG70ZW_-TQxHExbu8gjhH-haIg0EuiWgJSxkL45jE1B4xWaOQNQXgJtmb7i1bSVcRgdmJq0XbttjsZnZn3YTW_LYw_3F-WyEEryTRritkZm6CW6NgaoVUfGH6XIaHp5Igs_dzm01lci9XwvoUwS0KA85w3npkjseL0zZX6u-pYWbSXOzkTLDJDMKPpOPt1VH6UUwARlD1YH1dQb0qdq4FrN8_beghJc00UaO9WHgyLyQ-NXMXFt5zXpeKuWtGwWtB0bzDhEvUXUhoDeOwaTbHlEjv3NgrqfzzpLBfLMM9J2BZLZodaEFA6WiroIsq70Qh6g_yMCVg02oi3s-L_2SSW2duayIIcfljyOxmC5AHbjzS2i-4RnKlVzK5Ge39wmiXX_4wtL0nb5XeDPwGbqqJsCPaeIYFN7z43HW6bA--5E3pUo3mjxLPTMSa8T-omZIw7w=w1896-h835-l75";
function loadNew(){
imgLut.crossOrigin = "Anonymous2";
imgLut.onload = function() {
canvasLut.width = imgLut.width;
canvasLut.height = imgLut.height;
ctxLut.drawImage( imgLut, 0, 0 );
filterImage(img, imgLut, canvasLut, ctxLut);
localStorage.setItem( "savedImageDataLut", canvasLut.toDataURL("image/png") );
}
imgLut.src = srcLutbyte;
// make sure the load event fires for cached images too
if ( imgLut.complete || imgLut.complete === undefined ) {
imgLut.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
imgLut.src = srcLutbyte;
}
}
function alternateImage(img, canvastoapply, ctxToApply){
//var c=document.getElementById("myCanvas");
//var img=document.getElementById("scream");
ctxToApply.drawImage(img,0,0);
var imgData=ctxToApply.getImageData(0,0,canvastoapply.width,canvastoapply.height);
// invert colors
for (var i=0;i<imgData.data.length;i+=4){
imgData.data[i]=255-imgData.data[i];
imgData.data[i+1]=255-imgData.data[i+1];
imgData.data[i+2]=255-imgData.data[i+2];
imgData.data[i+3]=255;
}
ctxToApply.putImageData(imgData,0,0);
};
function filterImage(img, filter, canvastoapply, ctxToApply){
//var c=document.getElementById("myCanvas");
//var img=document.getElementById("scream");
// ctxToApply.drawImage(img,0,0);
var lutWidth = canvasLut.width;
var imgData=ctx.getImageData(0,0,canvas.width,canvas.height);
var filterData=ctxToApply.getImageData(0,0,canvastoapply.width,canvastoapply.height);
// invert colors
for (var i=0;i<imgData.data.length;i+=4){
var r=Math.floor(imgData.data[i]/4);
var g=Math.floor(imgData.data[i+1]/4);
var b=Math.floor(imgData.data[i+2]/4);
var a=255;
var lutX = (b % 8) * 64 + r;
var lutY = Math.floor(b / 8) * 64 + g;
var lutIndex = (lutY * lutWidth + lutX)*4;
var Rr = filterData.data[lutIndex];
var Gg = filterData.data[lutIndex+1];
var Bb = filterData.data[lutIndex+2];
imgData.data[i] = filterData.data[lutIndex];
imgData.data[i+1] = filterData.data[lutIndex+1];
imgData.data[i+2] = filterData.data[lutIndex+2];
imgData.data[i+3] = 255;
}
ctx.putImageData(imgData,0,0);
for the attached LUT and it does not work properly because it only has 5 colums instead of 8. Of course I read the comment from How to use LUT with JavaScript? which says "This code only applies for 64x64x64 3DLUT images. The parameters vary if your LUT has other dimensions; the / 4, * 64, % 8, / 8 must be changed for other dimensions, but in this question's scope the LUT is 64x64x64."
i tried to do so and only ended in a mess.
What would I please have to change to make it work?
I want to capture whole div as image and save on local for proof.I have searched and read many articles about svg to image or div to image.
I have tried some js library for this.But when i try to capture image from div then some captures only div content and some captures only svg content.
s.jpg , a.jpg
html2canvas(contentDiv, {
onrendered: function(can) {
dirty.appendChild(can);
}
});
// first convert your svg to png
exportInlineSVG(svg, function(data, canvas) {
svg.parentNode.replaceChild(canvas, svg);
// then call html2canvas
html2canvas(contentDiv, {
onrendered: function(can) {
can.id = 'canvas';
clean.appendChild(can);
}
});
})
function exportInlineSVG(svg, receiver, params, quality) {
if (!svg || !svg.nodeName || svg.nodeName !== 'svg') {
console.error('Wrong arguments : should be \n exportSVG(SVGElement, function([dataURL],[canvasElement]) || IMGElement || CanvasElement [, String_toDataURL_Params, Float_Params_quality])')
return;
}
var xlinkNS = "http://www.w3.org/1999/xlink";
var clone;
// This will convert an external image to a dataURL
var toDataURL = function(image) {
var img = new Image();
// CORS workaround, this won't work in IE<11
// If you are sure you don't need it, remove the next line and the double onerror handler
// First try with crossorigin set, it should fire an error if not needed
img.crossOrigin = 'Anonymous';
img.onload = function() {
// we should now be able to draw it without tainting the canvas
var canvas = document.createElement('canvas');
var bbox = image.getBBox();
canvas.width = bbox.width;
canvas.height = bbox.height;
// draw the loaded image
canvas.getContext('2d').drawImage(this, 0, 0, bbox.width, bbox.height);
// set our original <image>'s href attribute to the dataURL of our canvas
image.setAttributeNS(xlinkNS, 'href', canvas.toDataURL());
// that was the last one
if (++encoded === total) exportDoc()
}
// No CORS set in the response
img.onerror = function() {
// save the src
var oldSrc = this.src;
// there is an other problem
this.onerror = function() {
console.warn('failed to load an image at : ', this.src);
if (--total === encoded && encoded > 0) exportDoc();
}
// remove the crossorigin attribute
this.removeAttribute('crossorigin');
// retry
this.src = '';
this.src = oldSrc;
}
// load our external image into our img
img.src = image.getAttributeNS(xlinkNS, 'href');
}
// The final function that will export our svgNode to our receiver
var exportDoc = function() {
// check if our svgNode has width and height properties set to absolute values
// otherwise, canvas won't be able to draw it
var bbox = svg.getBBox();
// avoid modifying the original one
clone = svg.cloneNode(true);
if (svg.width.baseVal.unitType !== 1) clone.setAttribute('width', bbox.width);
if (svg.height.baseVal.unitType !== 1) clone.setAttribute('height', bbox.height);
parseStyles();
// serialize our node
var svgData = (new XMLSerializer()).serializeToString(clone);
// remember to encode special chars
var svgURL = 'data:image/svg+xml; charset=utf8, ' + encodeURIComponent(svgData);
var svgImg = new Image();
svgImg.onload = function() {
// if we set a canvas as receiver, then use it
// otherwise create a new one
var canvas = (receiver && receiver.nodeName === 'CANVAS') ? receiver : document.createElement('canvas');
// IE11 doesn't set a width on svg images...
canvas.width = this.width || bbox.width;
canvas.height = this.height || bbox.height;
canvas.getContext('2d').drawImage(this, 0, 0, canvas.width, canvas.height);
// try to catch IE
try {
// if we set an <img> as receiver
if (receiver.nodeName === 'IMG') {
// make the img looks like the svg
receiver.setAttribute('style', getSVGStyles(receiver));
receiver.src = canvas.toDataURL(params, quality);
} else {
// make the canvas looks like the canvas
canvas.setAttribute('style', getSVGStyles(canvas));
// a container element
if (receiver.appendChild && receiver !== canvas)
receiver.appendChild(canvas);
// if we set a function
else if (typeof receiver === 'function')
receiver(canvas.toDataURL(params, quality), canvas);
}
} catch (ie) {
console.warn("Your ~browser~ has tainted the canvas.\n The canvas is returned");
if (receiver.nodeName === 'IMG') receiver.parentNode.replaceChild(canvas, receiver);
else receiver(null, canvas);
}
}
svgImg.onerror = function(e) {
if (svg._cleanedNS) {
console.error("Couldn't export svg, please check that the svgElement passed is a valid svg document.");
return;
}
// Some non-standard NameSpaces can cause this issues
// This will remove them all
function cleanNS(el) {
var attr = el.attributes;
for (var i = 0; i < attr.length; i++) {
if (attr[i].name.indexOf(':') > -1) el.removeAttribute(attr[i].name)
}
}
cleanNS(svg);
for (var i = 0; i < svg.children.length; i++)
cleanNS(svg.children[i]);
svg._cleanedNS = true;
// retry the export
exportDoc();
}
svgImg.src = svgURL;
}
// ToDo : find a way to get only usefull rules
var parseStyles = function() {
var styleS = [],i;
// transform the live StyleSheetList to an array to avoid endless loop
for (i = 0; i < document.styleSheets.length; i++)
styleS.push(document.styleSheets[i]);
// Do we have a `<defs>` element already ?
var defs = clone.querySelector('defs') || document.createElementNS('http://www.w3.org/2000/svg', 'defs');
if (!defs.parentNode)
clone.insertBefore(defs, clone.firstElementChild);
// iterate through all document's stylesheets
for (i = 0; i < styleS.length; i++) {
var style = document.createElement('style');
var rules = styleS[i].cssRules,
l = rules.length;
for (var j = 0; j < l; j++)
style.innerHTML += rules[j].cssText + '\n';
defs.appendChild(style);
}
// small hack to avoid border and margins being applied inside the <img>
var s = clone.style;
s.border = s.padding = s.margin = 0;
s.transform = 'initial';
}
var getSVGStyles = function(node) {
var dest = node.cloneNode(true);
svg.parentNode.insertBefore(dest, svg);
var dest_comp = getComputedStyle(dest);
var svg_comp = getComputedStyle(svg);
var mods = "";
for (var i = 0; i < svg_comp.length; i++) {
if (svg_comp[svg_comp[i]] !== dest_comp[svg_comp[i]])
mods += svg_comp[i] + ':' + svg_comp[svg_comp[i]] + ';';
}
svg.parentNode.removeChild(dest);
return mods;
}
var images = svg.querySelectorAll('image'),
total = images.length,
encoded = 0;
// Loop through all our <images> elements
for (var i = 0; i < images.length; i++) {
// check if the image is external
if (images[i].getAttributeNS(xlinkNS, 'href').indexOf('data:image') < 0)
toDataURL(images[i]);
// else increment our counter
else if (++encoded === total) exportDoc()
}
// if there were no <image> element
if (total === 0) exportDoc();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<div id="contentDiv" style="width: 50%;">
<img class="" src="s.jpg" width="75%">
<svg xmlns="http://www.w3.org/2000/svg" id="svg" height="100%">
<defs>
<clipPath id="my-path">
<text id="texty" style="font-weight:bold;" x="60" y="300" font-size="60">test</text>
</clipPath>
</defs>
<image xlink:href="a.jpg" clip-path="url(#my-path)" width="100%" height="100%" id="filler" preserveAspectRatio="none"></image>
</svg>
</div>
<div id="clean">clean:<br></div>
<div id="dirty">dirty :<br></div>
<style type="text/css">
svg {
position: relative;
top: -531px;
left: 120px;
}
</style>
I have attached three images. s.jpg image is my main image which is inside in main div. It is main image where user can write their name with texture color. To write text i have used svg inside main div and for texture i have used a.jpg as hidden image.
I used html2canvas js library to convert div into image but i did not get my desired output. Please help me to find out solution for this problem. Thanx in advance
Try this, very easy to use and works everytime :
Dom-To-Image
you can use saveSvgAsPng.js where you have to pass the svg element id along with file name to the image
in my case
saveSvgAsPng(document.getElementById('canvassvg'), "structure.png");
which stores the image in your temp or browser downloads location
(OR)
if you want to store it on server
convert the innerhtml content of of your main tag , i.e., from svg to /svg to base64 and use the base64 to image converter in the backend
var svgData = new XMLSerializer().serializeToString( svgobj );
var canvas = document.createElement( "canvas" );
var ctx = canvas.getContext( "2d" );
var img = document.createElement( "img" );
function toSolidBytes(match, p1) {
return String.fromCharCode('0x' + p1);
})));
svgData= btoa(encodeURIComponent(svgData).replace(/%([0-9A-F]{2})/g,
function toSolidBytes(match, p1) {
return String.fromCharCode('0x' + p1);
}));
img.setAttribute( "src", "data:image/svg+xml;base64," + svgData );
var canvasd='';
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage( img, 0, 0 );
canvasd = canvas.toDataURL( "image/svg+xml" );
-base64 data is in canvasd
-ajax call to store to backend
};
return;
I'm trying to understand javascript before going to jQuery and I made a simple image slider.
I ended up with the following code working well when I manually start it on browser console, and I can't figure out how to start it and if using Promise would do, and how.
Reduced code:
/*some variable declarations and value assignations*/
function cut(p1){
for (var i = 0; i < cuts; i++){
/*canvas working with path pattern and fill*/
slice[p1][i] = new Image();
slice[p1][i].src = canvas.toDataURL();
}
}
function slider(){
/*time based image selection and canvas clear*/
for (var i = 0; i < 10; i++){
y = /*timebased calc*/;
if(y<0){y=0;}
ctx.drawImage(slice[im][i], 0, y);
}
window.requestAnimationFrame(slider);
}
img[0].onload = function() {cut(0);};
img[1].onload = function() {cut(1);};
Full code:
var height = 500, width = 707, cuts = 10, cW = Math.ceil(width/cuts);
var img = [new Image(), new Image()];
var slice = [];
for (var i = 0; i < img.length; i++){
slice[i] = [];
}
var x = [];
for (var i=0; i<cuts; i++){
x[i]=Math.ceil(((i+1)*width)/cuts);
}
function cut(p1){
for (var i = 0; i < cuts; i++){
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');
var pat = context.createPattern( img[p1], 'no-repeat' );
context.fillStyle = pat;
context.beginPath();
context.moveTo(x[i], 0);
context.lineTo(x[i], height);
context.lineTo(x[i]-cW, height);
context.lineTo(x[i]-cW, 0);
context.closePath();
context.fill();
slice[p1][i] = new Image();
slice[p1][i].src = canvas.toDataURL();
}
}
var canv = document.createElement('canvas');
document.body.appendChild(canv);
canv.width = width;
canv.height = height;
var ctx = canv.getContext('2d');
var sTime= 0;
function slider(){
var t = (performance.now() - sTime) % 10000;
if(t%5000 === 2000){
ctx.clear();
}
var im = 0;
if(t >= 5000){
im = 1;
} else {
im = 0;
}
for (var i = 0; i < 10; i++){
t = t%5000;
y = 2000-((t)+(i*100));
if(y<0){y=0;}
ctx.drawImage(slice[im][i], 0, y);
}
window.requestAnimationFrame(slider);
}
CanvasRenderingContext2D.prototype.clear = function () {this.clearRect(0, 0, this.canvas.width, this.canvas.height);}
img[0].onload = function() {cut(0);};
img[1].onload = function() {cut(1);};
img[0].src = 'mountain.jpg';
img[1].src = 'beach.jpg';
Haven't tested this but it might come close:
function imageLoader(imagePaths, onLoad, onFinished) {
var images = [];
var arrayLength = imagePaths.length;
function callback() {
if(--arrayLength === 0) onFinished();
}
imagePaths.forEach(function(imagePath, index) {
var image = new Image();
image.onload(onLoad(index, callback));
image.src = imagePath;
images[index] = image;
});
return images;
}
modify cut() to:
function cut(p1, cb){
//.
//.
//.
cb();
}
replace
img[0].onload = function() {cut(0);};
img[1].onload = function() {cut(1);};
img[0].src = 'mountain.jpg';
img[1].src = 'beach.jpg';
with:
img = imageLoader(['mountain.jpg', 'beach.jpg'], cut, slider);
currelty working on a small matching puzzle game. Currently it displays text for the time remaining and the number of tiles that have been macthes. I'm trying to create on for best completion time as well (How fast the person finishes the game) however have been running into a lot of problems. for two variables that I created "txt" and "matchesFoundText" when I type them the autocomplete box will popup and ".text" is displayed as one of the options so i would get something like "txt.text. however I'm not getting that option at all for "bestTimeTxt" and I have no idea as to why this is happening. I did all three variables the same way so I'm at a loss as to why Text is not available to select from for "bestTimeTxt". Here is my entire script.
<!DOCTYPE html>
<html>
<head>
<title>Recipe: Drawing a square</title>
<script src="easel.js"></script>
<script type="text/javascript">
var canvas;
var stage;
var squareSide = 70;
var squareOutline = 5;
var max_rgb_color_value = 255;
var gray = Graphics.getRGB(20, 20, 20);
var placementArray = [];
var tileClicked;
var timeAllowable;
var totalMatchesPossible;
var matchesFound;
var txt;
var bestTime;
var bestTimeTxt;
var matchesFoundText;
var squares;
function init() {
var rows = 5;
var columns = 6;
var squarePadding = 10;
canvas = document.getElementById('myCanvas');
stage = new Stage(canvas);
var numberOfTiles = rows*columns;
matchesFound = 0;
timeAllowable = 5;
bestTime = 0;
txt = new Text(timeAllowable, "30px Monospace", "#000");
txt.textBaseline = "top"; // draw text relative to the top of the em box.
txt.x = 500;
txt.y = 0;
bestTimeTxt = new Text(bestTime, "30px Monospace", "#000");
bestTimeTxt.textBaseLine = "top";
bestTimeTxt.x = 500;
bestTimeTxt.y = 80;
stage.addChild(txt);
stage.addChild(bestTimeTxt);
squares = [];
totalMatchesPossible = numberOfTiles/2;
Ticker.init();
Ticker.addListener(window);
Ticker.setPaused(false);
matchesFoundText = new Text("Pairs Found: "+matchesFound+"/"+totalMatchesPossible, "30px Monospace", "#000");
matchesFoundText.textBaseline = "top"; // draw text relative to the top of the em box.
matchesFoundText.x = 500;
matchesFoundText.y = 40;
stage.addChild(matchesFoundText);
setPlacementArray(numberOfTiles);
for(var i=0;i<numberOfTiles;i++){
var placement = getRandomPlacement(placementArray);
if (i % 2 === 0){
var color = randomColor();
}
var square = drawSquare(gray);
square.color = color;
square.x = (squareSide+squarePadding) * (placement % columns);
square.y = (squareSide+squarePadding) * Math.floor(placement / columns);
squares.push(square);
stage.addChild(square);
square.cache(0, 0, squareSide + squarePadding, squareSide + squarePadding);
square.onPress = handleOnPress;
stage.update();
};
}
function drawSquare(color) {
var shape = new Shape();
var graphics = shape.graphics;
graphics.setStrokeStyle(squareOutline);
graphics.beginStroke(gray);
graphics.beginFill(color);
graphics.rect(squareOutline, squareOutline, squareSide, squareSide);
return shape;
}
function randomColor(){
var color = Math.floor(Math.random()*255);
var color2 = Math.floor(Math.random()*255);
var color3 = Math.floor(Math.random()*255);
return Graphics.getRGB(color, color2, color3)
}
function setPlacementArray(numberOfTiles){
for(var i = 0;i< numberOfTiles;i++){
placementArray.push(i);
}
}
function getRandomPlacement(placementArray){
randomNumber = Math.floor(Math.random()*placementArray.length);
return placementArray.splice(randomNumber, 1)[0];
}
function handleOnPress(event){
var tile = event.target;
tile.graphics.beginFill(tile.color).rect(squareOutline, squareOutline, squareSide, squareSide);
if(!!tileClicked === false || tileClicked === tile){
tileClicked = tile;
tileClicked.updateCache("source-overlay");
}else{
if(tileClicked.color === tile.color && tileClicked !== tile){
tileClicked.visible = false;
tile.visible = false;
matchesFound++;
matchesFoundText.text = "Pairs Found: "+matchesFound+"/"+totalMatchesPossible;
if (matchesFound===totalMatchesPossible){
gameOver(true);
}
}else{
tileClicked.graphics.beginFill(gray).rect(squareOutline, squareOutline, squareSide, squareSide);
}
tileClicked.updateCache("source-overlay");
tile.updateCache("source-overlay");
tileClicked = tile;
}
stage.update();
}
function tick() {
secondsLeft = Math.floor((timeAllowable-Ticker.getTime()/1000));
txt.text = secondsLeft;
;
if (secondsLeft <= 0){
gameOver(false);
}
stage.update();
}
function gameOver(win){
Ticker.setPaused(true);
for(var i=0;i<squares.length;i++){
squares[i].graphics.beginFill(squares[i].color).rect(5, 5, 70, 70);
squares[i].onPress = null;
if (win === false){
squares[i].uncache();
}
}
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play Again?</a>";
if (win === true){
matchesFoundText.text = "You win!"
}else{
txt.text = secondsLeft + "... Game Over";
}
}
function replay(){
init();
}
</script>
</head>
<body onload="init()">
<header id="header">
<p id="replay"></p>
</header>
<canvas id="myCanvas" width="960" height="400"></canvas>
</body>
</html>
Okay so apparently the reason why I was having issues is because the x and y positions of the bestTimeTxt variable was causing it to be obscured by the position of everything else.
#cap is a div i want to capture.
I used ctx.drawImage($('#cap').get(0),0,0,640,480);window.open(canvas.getDataURL('image/jpeg'));
got a Type error
and how do i send it to php to save as a.jpeg
UPDATE
http://jsfiddle.net/3qNJB/ is not working help html2canvas is not a function
< DIV > elements cannot be drawn on canvas using drawImage() method.Have a look at Html2Canvas library
Example:
html2canvas(document.getElementById('DivToCapture'), {
onrendered: function(canvas) {
// document.body.appendChild(canvas);
window.open(canvas.toDataURL('image/jpeg'));
}
});
Heres the Fiddle
Instead of opening the image with javascript, just POST it to your server so PHP can receive it, save it on the server, and then send it back to the browser.
I found this DivsToJPG() function here: Convert html div having multiple images to single image using javascript
var DivsToJPG = function( parent ) {
this.canvasSizeX = 0;
this.canvasSizeY = 0;
this.init = function( parent ) {
this.images = parent.find('img');
this.setSizes();
this.createCanvas();
this.drawImages();
this.exportJPG();
}
this.setSizes = function() {
for (var i = 0, l = this.images.length; i < l ; i++) {
var currentImage = this.images.eq(i);
var posX = currentImage.position().left;
var width = currentImage.width();
this.canvasSizeX = this.canvasSizeX > (posX+width) ? this.canvasSizeX : posX + width;
//console.log(this.canvasSizeX);
var posY = currentImage.position().top;
var height = currentImage.height();
this.canvasSizeY = this.canvasSizeY > (posY+height) ? this.canvasSizeY : posY + height;
}
}
this.createCanvas = function() {
this.canvas = document.createElement('canvas');
this.canvas.id = "exportCanvas";
this.canvas.width = this.canvasSizeX;
this.canvas.height = this.canvasSizeY;
this.ctx = this.canvas.getContext("2d");
document.body.appendChild(this.canvas);
}
this.drawImages = function() {
for (var i = 0, l = this.images.length; i < l ; i++) {
var currentImage = this.images[i];
var $currentImage = this.images.eq(i);
this.ctx.drawImage(currentImage, $currentImage.position().left, $currentImage.position().top, $currentImage.width(), $currentImage.height());
}
}
this.exportJPG = function() {
var dataURL = this.canvas.toDataURL();
this.img = document.createElement('img');
this.img.id = "createdImage";
this.img.src = dataURL;
document.body.appendChild(this.img);
}
this.init( parent );
}
var divsToJPG = new DivsToJPG($('#cap'));
$.ajax({
type : "POST",
url : "make-image.php",
data : {
imgBase64 : divsToJPG
}
}).done(function(data) {
});
Then in PHP
$img = base64_decode($_POST['imgBase64']);