I need to save all drawings from my canvas in order to be able to return to them later on.
I succeed in getting and putting data but I can't save the object and return it correctly.
This is my code:
var imgData = a.getImageData(0, 0, 500, 200);
localStorage.setItem("test",JSON.stringify(imgData))
console.log(imgData)
console.log(JSON.parse(localStorage.getItem("test")))
b.putImageData(imgData, 0, 0);
You can use the canvas.toDataURL() method which will encode the canvas into Base64.
You can then create a image with the source being the data url and then draw that image to the canvas.
Here is the working sample.
var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
var url = canvas.toDataURL();
localStorage.setItem('url', url);
var canvas2 = document.getElementById('tutorial2');
var ctx2 = canvas2.getContext("2d");
var toDrawUrl = localStorage.getItem('url');
drawDataURIOnCanvas(toDrawUrl, ctx2);
ctx2.fillStyle = "rgb(200,200,0)";
ctx2.fillRect (20, 20, 55, 50);
function drawDataURIOnCanvas(strDataURI, context) {
"use strict";
var img = new window.Image();
img.addEventListener("load", function () {
context.drawImage(img, 0, 0);
});
img.setAttribute("src", strDataURI);
}
i want to save the huge data as imagedate in local-storage you must be convert from buffer to string and used this functions
function buf2str(buf) {
var bufView = new Uint16Array(buf);
var unis =""
for (var i = 0; i < bufView.length; i++) {
unis=unis+String.fromCharCode(bufView[i]);
}
return unis
}
to reverse function use this function
function str2buf(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
i has success to save data and edit it after callback
my code is
var canvasData={
_save:function(from,id){
var imgData = from.getImageData(0, 0, el.width, el.height);
var buffer = imgData.data.buffer;
var testV=ab2str(buffer);
try {
localStorage.setItem(id+"Length",testV._length)
localStorage.setItem(id+"Keys",testV._keys)
localStorage.setItem(id+"Data",testV._Data)
} catch(e) {
var storageSize = Math.round(JSON.stringify(localStorage).length / 1024);
console.log("LIMIT REACHED: (" + i + ") " + storageSize + "K");
console.log(e);
alert("your localStorage is complete , you must delete some nots or markers to be can store again ")
}
},
_return:function(to,id){
var tempObj={_Length:0,_Keys:"",_Data:""}
try {
tempObj._Length= localStorage.getItem(id+"Length")
tempObj._Keys= localStorage.getItem(id+"Keys")
tempObj._Data= localStorage.getItem(id+"Data")
} catch(e) {
var storageSize = Math.round(JSON.stringify(localStorage).length / 1024);
console.log("LIMIT REACHED: (" + i + ") " + storageSize + "K");
console.log(e);
}
if (tempObj ==null ){return false};
if (tempObj._Length ==null ){return false};
if (tempObj._Keys ==null ){return false};
if (tempObj._Data ==null ){return false};
var temp=tempObj._Length.split(",");
var newWidth=parseInt(temp[0]);
var newHeight= parseInt(temp[1]);
var newImgData = to.createImageData(newWidth,newHeight);
var incomingBuffer=returnOriginalBuffer(tempObj)
newImgData.data.set(new Uint8Array(incomingBuffer))
to.putImageData(newImgData, 0, 0);
}
}
function ab2str(buf) {
var bufView = new Uint16Array(buf);
var dataArr=new Array();
var dataStr =""
var keysStr =""
var lenStr=el.width.toString()+","+el.height.toString()
var returnedObj={_length:lenStr,_keys:"",_Data:""}
var dote="";
for (var q = 0; q < bufView.length; q++) {
if(bufView[q]!=0){
keysStr=keysStr+dote+q;
dote=","
dataArr.push(bufView[q]);
}
}
for (var w = 0; w < dataArr.length; w++) {
dataStr=dataStr+String.fromCharCode(dataArr[w]);
}
returnedObj._keys=keysStr;
returnedObj._Data=dataStr;
return returnedObj
}
function returnOriginalBuffer(tempObj) {
var temp=tempObj._Length.split(",");
var _length=parseInt(temp[0])*parseInt(temp[1])*2
var _keys=tempObj._Keys;
var _data=tempObj._Data;
var keysArr =new Array();
var dataArr=new Array();
keysArr=_keys.split(",")
for (var w=0, strLen=_data.length; w<strLen; w++) {
dataArr[w]=_data.charCodeAt(w) ;
}
var buf = new ArrayBuffer(_length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
var q=0
for (var i=0, strLen=_length; i<strLen; i++) {
if (i!=parseInt(keysArr[q])){
bufView[i] = 0;
}else{
bufView[i] = dataArr[q]
q++;
}
}
return buf;
}
//save data
canvasData._save(ctx,"localstoragename")
// return data
canvasData._return(ctx,"localstoragename")
this soluation is complex if any one own simple workaround, help us
Related
all i get is a little square with rgb(0,255,255) and i want the 'r' to be proportionate to the log (betterLog is a log function(base,answer)=exponent
everything
var ln = function(g){
var n=g;
n=abs(n);
if(n>1){
n=1/n;
}
var x=n-1;
var output = x;
var i;
for(i = 2; i < 99; i++){
if (i%2 === 0){
output -= pow(x,i)/i;
}
if (i%2 === 1){
output += pow(x,i)/i;
}
}
return output;
};
var betterLog = function(a,b){
var output = ln(b)/ln(a);
return output;
};
var v=475;
var block = function(){
this.render = function(){
var stupidColor=(betterLog(2,v)*20);
fill(stupidColor, 255, 255);
rect(20,20,20,20);
};
};
var newCrap = new block();
var draw = function() {
newCrap.render(v);
};
its just a rgb(0,255,255) idk if its rendering correct5ly or not im new to js and its just not working as wanted no errors per se
You just need to add the Mathobject to your functions
var ln = function(g){
var n=g;
n=Math.abs(n);
if(n>1){
n=1/n;
}
var x=n-1;
var output = x;
var i;
for(i = 2; i < 99; i++){
if (i%2 === 0){
output -= Math.pow(x,i)/i;
}
if (i%2 === 1){
output += Math.pow(x,i)/i;
}
}
return output;
};
var betterLog = function(a,b){
var output = ln(b)/ln(a);
return output;
};
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var fill = function(r,g,b,a){
ctx.fillStyle = 'rgba('+r+','+g+','+b+','+a||1+')';
};
var rect = function(x,y,w,h){
ctx.fillRect(x,y,w,h);
};
var v=475;
var block = function(){
this.render = function(v){
var stupidColor=(betterLog(2,v)*20);
fill(stupidColor, 255, 255);
console.log({stupidColor});
rect(20,20,20,20);
};
};
var newCrap = new block();
var draw = function() {
newCrap.render(v);
};
draw();
<canvas></canvas>
I use cordova and Framework7 for create app. My script load and show image from server fine, but if server return 404 I get alert 2 times. Why, and how can I fix it?
function view(a) {
var img = new Image();
var s = a;
myApp.showPreloader('Загружаем...');
img.src = s;
img.onload = function() {
document.getElementById('showimg').innerHTML = '';
var openPhotoSwipe = function(a) {
myApp.hidePreloader();
myApp.allowPanelOpen = false;
document.getElementById("check").style.display = "block";
var pswpElement = document.querySelectorAll('.pswp')[0];
var items = [{
src: s,
w: img.width,
h: img.height
}];
var options = {
showAnimationDuration: 0,
hideAnimationDuration: 0
};
var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
gallery.listen('destroy', function() {
document.getElementById("check").style.display = "none";
var elements = document.getElementsByTagName("input");
for (var ii = 0; ii < elements.length; ii++) {
if (elements[ii].type == "text") {
elements[ii].value = "";
}
}
$$(window).width() < 770 && (myApp.allowPanelOpen = !0);
});
};
openPhotoSwipe();
}
img.onerror = function() {
myApp.alert('Not found...');
myApp.hidePreloader();
}}
Try this:
function view(a) {
var img = new Image();
var s = a;
myApp.showPreloader('?????????...');
img.src = s;
var alertShown = false;
img.onload = function() {
document.getElementById('showimg').innerHTML = '';
var openPhotoSwipe = function(a) {
myApp.hidePreloader();
myApp.allowPanelOpen = false;
document.getElementById("check").style.display = "block";
var pswpElement = document.querySelectorAll('.pswp')[0];
var items = [{
src: s,
w: img.width,
h: img.height
}];
var options = {
showAnimationDuration: 0,
hideAnimationDuration: 0
};
var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
gallery.listen('destroy', function() {
document.getElementById("check").style.display = "none";
var elements = document.getElementsByTagName("input");
for (var ii = 0; ii < elements.length; ii++) {
if (elements[ii].type == "text") {
elements[ii].value = "";
}
}
$$(window).width() < 770 && (myApp.allowPanelOpen = !0);
});
};
openPhotoSwipe();
}
img.onerror = function() {
myApp.hidePreloader();
if(!alertShown){
alertShown = true;
myApp.alert('Not found...');
}
}}
}
I'm writing a tile game in JS and am loading a text based map with a XMLHttpRequest object. All works well until I actually try to draw the background. The map gets initialized, but it doesn't seem to be "fully" initialized by the time I try to loop through the rows. When I try to call map[rowNum].length I get an undefined error. In the debugger, I can see that once the code jumping back to loadMapHttp() which is where the XMLHttpRequest object is defined. I don't understand why it's doing this.
var map =[];
var tiles =[];
var background = new Image();
var canvas = document.getElementById("canvas");
var graphicsContext = canvas.getContext('2d');
background.src = "imgs/tileSheet.jpg";
function loadMapHttp() {
var conn = new XMLHttpRequest();
conn.onreadystatechange = handleStateChange;
conn.open("GET","map.txt",true);
conn.send();
function handleStateChange() {
if(conn.readyState === 4){
loadMap2(conn.status == 200 ? conn.responseText : null);
}
}
}
function loadMap2(text) {
if(text == null){
console.warn("Http Error");
return;
}
console.log("text received was: " + text);
var testMap = text;
var rows = testMap.split("\n");
for(var rowNum =0; rowNum < rows.length; rowNum++){
rows[rowNum] = rows[rowNum].trim();
map.push([]);
var cols = rows[rowNum].split("");
console.log(cols);
for(var colNum = 0; colNum<cols.length; colNum++){
map[rowNum][colNum] = cols[colNum];
}
}
}
function prepTiles() {
var TILESET_LEFT = 0;
var TILESET_TOP = 0;
var TILE_WIDTH = 31.2;
var TILE_HEIGHT = 31.2;
var tileCanvas = document.createElement('canvas');
var tileContext = tileCanvas.getContext('2d');
//BRICK
tileContext.drawImage(background, TILESET_TOP+TILE_WIDTH*2, TILESET_TOP, TILE_WIDTH, TILE_HEIGHT, 0, 0, TILE_WIDTH, TILE_HEIGHT);
tiles.push(tileContext.getImageData(0, 0, TILE_WIDTH, TILE_HEIGHT));
//DIRT
tileContext.drawImage(background, TILESET_LEFT+TILE_WIDTH*17, TILESET_TOP+TILE_HEIGHT*6, TILE_WIDTH, TILE_HEIGHT, 0, 0, TILE_WIDTH, TILE_HEIGHT);
tiles.push(tileContext.getImageData(0, 0, TILE_WIDTH, TILE_HEIGHT));
//GRASS
tileContext.drawImage(background, TILESET_LEFT+TILE_WIDTH*6, TILESET_TOP+TILE_HEIGHT*12, TILE_WIDTH, TILE_HEIGHT, 0, 0, TILE_WIDTH, TILE_HEIGHT);
tiles.push(tileContext.getImageData(0, 0, TILE_WIDTH, TILE_HEIGHT));
}
function getTile(char) {
if(char == 'B'){
return tiles[0];
}
if(char == 'D'){
return tiles[1];
}
if(char == 'G'){
return tiles[2];
}
}
function drawBackground(){
for(var rowNum=0; rowNum < 6; rowNum++){
console.log(map[rowNum]);
for(var colNum=0; colNum < map[rowNum].length; colNum++){
var tile = getTile(map[rowNum][colNum]);
graphicsContext.putImageData(tile, colNum*31, rowNum*31);
}
}
}
function startGame() {
loadMapHttp();
prepTiles();
drawBackground();
}
startGame();
var imgs = ['bmw.jpg', 'bugatti.jpg', 'classic.jpg', 'concept.jpg', 'corvette.jpg', 'dino.jpg', 'lambo.jpg', 'mcclaren.jpg', 'p1.jpg', 'porsche.jpg', 'rally.jpg', 'audi.jpg'];
// var imgs_count = {'bmw.jpg': 0, 'bugatti.jpg': 0, 'classic.jpg': 0, 'concept.jpg': 0, 'corvette.jpg': 0, 'dino.jpg': 0, 'lambo.jpg': 0, 'mcclaren.jpg': 0, 'p1.jpg': 0, 'porsche.jpg': 0,'rally.jpg': 0, 'audi.jpg':0}
// for (var i in imgs_count) {
// imgs_count[i]
// }
var allCars = [];
var votes;
function Car(file) {
this.file = file;
this.votes = 0;
allCars.push(this);
}
var bmw = new Car('bmw.jpg');
var bugatti = new Car('bugatti.jpg');
var classic = new Car('classic.jpg');
var concept = new Car('concept.jpg');
var corvette = new Car('corvette.jpg');
var dino = new Car('dino.jpg');
var lambo = new Car('lambo.jpg');
var mcclaren = new Car('mcclaren.jpg');
var p1 = new Car('p1.jpg');
var porsche =new Car('porsche.jpg');
var rally = new Car('rally.jpg');
var audi = new Car('audi.jpg');
var idx1 = 0;
var idx2 = 0;
var path = 'cars/';
var done = false;
function getRandomImage() {
idx1 = Math.floor(Math.random()*imgs.length);
var img1 = imgs[idx1];
idx2 = idx1;
while (idx2 == idx1) {
idx2 = Math.floor(Math.random()*imgs.length);
}
img2 = imgs[idx2];
document.getElementById('choice1').setAttribute('src', path + img1);
document.getElementById('choice2').setAttribute('src', path + img2);
}
function setOnClicks(id) {
document.getElementById(id).addEventListener('click', function(event) {
var choice = event.target.id;
if (choice === 'choice1') {
console.log(allCars);
var img = document.getElementById(id).getAttribute('src');
var allCars = img.slice(5,img.length);
this.allCars[idx1].votes += 1;
console.log(idx1);
console.log(this.allCars[idx1].votes)
if ( allCars[idx1].votes=3) {
done = true;
}
}
if (choice === 'choice2') {
var img = document.getElementById(id).getAttribute('src');
var allCars = img.slice(5,img.length);
console.log(idx2);
console.log(this.allCars[idx2].votes);
this.allCars[idx2].votes += 1;
if (allCars[idx2].votes == 3) {
done = true;
}
}
if (!done)
getRandomImage();
});
}
getRandomImage();
setOnClicks('choice1');
setOnClicks('choice2')l
You're overwriting your global allCars with a local var declaration of the same name:
var allCars = img.slice(5,img.length);
you are creating a local variable allCars under click event, while this.allCars is point to the allCars variable under window object
var allCars = img.slice(5,img.length); // this is a local variable
this.allCars[idx1].votes += 1; // this is same as window.allCars
console.log(idx1);
I am trying to desteghide an image to reveal the secret message.
I have got it working, but only by browsing the image which contains the message.
If you take a look at the screenshot:
To make this work I need to save the image (the arsenal badge). Then use the browse to upload the image again to make this work. I want to skip the browse stage and make automatically by grabbing the image straight from the div.
Any ideas?
here is my code (its quite messy sorry)
window.onload = function() {
// add action to the file input
var input = document.getElementById('file');
input.addEventListener('change', importImage);
};
var maxMessageSize = 1000;
$("#desteg").click(function()
{
decode();
});
var importImage = function(e) {
var reader = new FileReader();
reader.onload = function(event) {
// set the preview
document.getElementById('preview').style.display = 'block';
document.getElementById('preview').src = event.target.result;
// wipe all the fields clean
document.getElementById('pass').value = '';
document.getElementById('ContentArea').innerHTML = '';
// read the data into the canvas element
var img = new Image();
img.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.canvas.width = img.width;
ctx.canvas.height = img.height;
ctx.drawImage(img, 0, 0);
decode();
};
img.src = event.target.result;
};
reader.readAsDataURL(e.target.files[0]);
};
// encode the image and save it
// decode the image and display the contents if there is anything
var decode = function() {
var password = document.getElementById('pass').value;
var passwordFail = 'Password is incorrect or there is nothing here.';
// decode the message with the supplied password
var ctx = document.getElementById('canvas').getContext('2d');
var imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
var message = decodeMessage(imgData.data, sjcl.hash.sha256.hash(password));
// try to parse the JSON
var obj = null;
try {
obj = JSON.parse(message);
} catch (e) {
// display the "choose" view
if (password.length > 0) {
alert(passwordFail);
}
}
// display the "reveal" view
if (obj) {
// decrypt if necessary
if (obj.ct) {
try {
obj.text = sjcl.decrypt(password, message);
} catch (e) {
alert(passwordFail);
}
}
// escape special characters
var escChars = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
'\'': ''',
'/': '/',
'\n': '<br/>'
};
var escHtml = function(string) {
return String(string).replace(/[&<>"'\/\n]/g, function (c) {
return escChars[c];
});
};
document.getElementById('ContentArea').innerHTML = escHtml(obj.text);
}
};
// returns a 1 or 0 for the bit in 'location'
var getBit = function(number, location) {
return ((number >> location) & 1);
};
// sets the bit in 'location' to 'bit' (either a 1 or 0)
var setBit = function(number, location, bit) {
return (number & ~(1 << location)) | (bit << location);
};
// returns an array of 1s and 0s for a 2-byte number
var getBitsFromNumber = function(number) {
var bits = [];
for (var i = 0; i < 16; i++) {
bits.push(getBit(number, i));
}
return bits;
};
// returns the next 2-byte number
var getNumberFromBits = function(bytes, history, hash) {
var number = 0, pos = 0;
while (pos < 16) {
var loc = getNextLocation(history, hash, bytes.length);
var bit = getBit(bytes[loc], 0);
number = setBit(number, pos, bit);
pos++;
}
return number;
};
// returns an array of 1s and 0s for the string 'message'
var getMessageBits = function(message) {
var messageBits = [];
for (var i = 0; i < message.length; i++) {
var code = message.charCodeAt(i);
messageBits = messageBits.concat(getBitsFromNumber(code));
}
return messageBits;
};
// gets the next location to store a bit
var getNextLocation = function(history, hash, total) {
var pos = history.length;
var loc = Math.abs(hash[pos % hash.length] * (pos + 1)) % total;
while (true) {
if (loc >= total) {
loc = 0;
} else if (history.indexOf(loc) >= 0) {
loc++;
} else if ((loc + 1) % 4 === 0) {
loc++;
} else {
history.push(loc);
return loc;
}
}
};
// encodes the supplied 'message' into the CanvasPixelArray 'colors'
// returns the message encoded in the CanvasPixelArray 'colors'
var decodeMessage = function(colors, hash) {
// this will store the color values we've already read from
var history = [];
// get the message size
var messageSize = getNumberFromBits(colors, history, hash);
// exit early if the message is too big for the image
if ((messageSize + 1) * 16 > colors.length * 0.75) {
return '';
}
// exit early if the message is above an artificial limit
if (messageSize === 0 || messageSize > maxMessageSize) {
return '';
}
// put each character into an array
var message = [];
for (var i = 0; i < messageSize; i++) {
var code = getNumberFromBits(colors, history, hash);
message.push(String.fromCharCode(code));
}
// the characters should parse into valid JSON
return message.join('');
};