I'm running following code in both Chrome and Firefox up-to-date versions.
window.onload = function()
{
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e)
{
var fileCount=fileInput.files.length;
for(var i=0;i<fileCount;i++)
{
var file = fileInput.files[i];
var reader = new FileReader();
reader.onload = function(e)
{
var screenshotImage = new Image();
screenshotImage.onload = function()
{
var canvas = document.createElement('canvas');
canvas.id = makeid(5);
var canvasContext = canvas.getContext('2d');
canvas.width = this.width;
canvas.height = this.height;
canvasContext.drawImage(this,0,0,this.width, this.height);
var imgd = canvasContext.getImageData(0,0,canvas.width,canvas.height);
imagePxielData.push(imgd.data);
document.body.appendChild(canvas);
}
screenshotImage.src = this.result;
}
reader.readAsDataURL(file);
}
});
}
function readData()
{
for(var i=0;i<imageCount;i++)
{
var imgdata=imagePxielData[i];
tmp=0;
for (var j = 0, n = imgdata.length; j < n; j += 4)
{
var r = imgdata[j];
var g = imgdata[j+1];
var b = imgdata[j+2];
if(tmp<100)
console.log("r=>"+r+"g=>"+g+"b=>"+b);
tmp++;
}
}
}
After running by uploading an image, the first 100 RGB values shows different values in Chrome and Firefox. Chrome shows the correct values and Firefox show different values(incorrect values).
Why is this showing different values ?
How can fix this to display correct RGB values in both Chrome and Firefox ?
Thank you.
Related
Everything else in my game works except for the floor. Does anyone know why this doesn't work.
var floor = [];
var canvas = document.getElementById('bg');
var ctx = canvas.getContext('2d');
let posYFloor = 0;
for(i = 0; i < 9; i++)
{
floor[i] = new Image();
floor[i].src = "Bricks.png";
floor[i].onload=function()
{
ctx.drawImage(floor[i],i*50,posYFloor);
}
}
I managed to fix it. I realised that I didn't even need floor[i] at any point and I had a separate setInterval.
var floor = [];
var canvas = document.getElementById('bg');
var ctx = canvas.getContext('2d');
let posYFloor = 0;for(let i = 0; i < 25; i++)
{
floor = new Image();
floor.src = "Bricks.png";
floor.onload=function()
{
ctx.drawImage(floor,i*50,posYFloor);
}
}
setInterval(function() {
for(let i = 0; i < 25; i++)
{
ctx.drawImage(floor, i*50, posYFloor);
}
},1);
}
I have a following code that displays random images from array.
It generates random images, but however it fails to load unique image.
For more info i would like to add that this code is for Solitaire game so i need to generate unique image.
var imgArray = ['c1.png', 'c2.png', 'd3.png', 'd4.png', 'h5.png', 'h6.png', 'd7.png', 'h8.png'];
var basePath="card/";
function imgRandom() {
for (var i = 2; i < 8; i++) {
var rand = imgArray[Math.floor(Math.random() * imgArray.length)];
var image = new Image();
image.src = basePath+rand;
image.id = 'imageid';
image.width = '100';
image.height = '130';
image.style.position = 'absolute';
document.getElementById('myimg'+i).appendChild(image);
}
}
var imgArray = ['c1.png', 'c2.png', 'd3.png', 'd4.png', 'h5.png', 'h6.png', 'd7.png', 'h8.png'];
var basePath="card/";
function imgRandom() {
var imgArrayCopy = imgArray.slice(0); //make a copy of the array.
for (var i = 2; i < 8; i++) {
var rNumber = Math.floor(Math.random() * imgArrayCopy.length);
var rand = imgArrayCopy.splice(rNumber, 1); //deletes the img from the array and returns it;
var image = new Image();
image.src = basePath+rand;
image.id = 'imageid';
image.width = '100';
image.height = '130';
image.style.position = 'absolute';
document.getElementById('myimg'+i).appendChild(image);
}
}
This should do that.
Guys i am implementing an upload with resized image preview. the script is working, but the resize function is called many times for each img that i upload... why is this happening?
the example:
http://jsfiddle.net/LL4Dj/
and here's my code:
<form action="action" method="method">
<input type="file" id="uploads" name="img[]" multiple />
<button class="button">Enviar</button>
</form>
<div id="preview"></div>
Script
<script type="text/javascript">
function imageResize(e) {
console.log('TIMES');
var MAXWidthHeight = 100;
var r = MAXWidthHeight / Math.max(this.width, this.height),
w = Math.round(this.width * r),
h = Math.round(this.height * r),
c = document.createElement('canvas');
c.width = w;
c.height = h;
c.getContext("2d").drawImage(this, 0, 0, w, h);
this.src = c.toDataURL();
var li = document.createElement('li');
li.appendChild(this);
document.getElementById('preview').appendChild(li);
}
function previewImages() {
var fileList = this.files;
var anyWindow = window.URL || window.webkitURL;
var len = (fileList.length < 4) ? fileList.length : 4;
for (var i = 0; i < len; i++) {
var objectUrl = anyWindow.createObjectURL(fileList[i]);
var img = new Image();
img.onload = imageResize;
img.src = objectUrl;
window.URL.revokeObjectURL(fileList[i]);
}
}
var inputFile = document.getElementById('uploads');
inputFile.addEventListener('change', previewImages, false);
</script>
Its is happening because of these two lines in your < script >,
var inputFile = document.getElementById('uploads');
inputFile.addEventListener('change', previewImages, false);
When ever an image is selected, the "change" event will be triggered and "previewImages()" function will be called.
i'm trying to build a waveform generator that get audiofile amplitudes values and display them to a canvas as quick as possible (faster than realtime) in javascript. so i use the OfflineAudioContext / webkitOfflineAudioContext , load the file and start the analyse.
the waveform is to fill a wide canvas.
i analyse buffer in a processor.onaudioprocess function. (i guess it's the way it works ?)
it works fine in firefox but i've got an issue in chrome : it seems it "jumps" over much analyse to finish it works as soon as possible and only returns a few coordinates (something like 16).
here is the jsfiddle :
http://jsfiddle.net/bestiole/95EBf/
// create the audio context
if (! window.OfflineAudioContext) {
if (! window.webkitOfflineAudioContext) {
$('#output').append('failed : no audiocontext found, change browser');
}
window.OfflineAudioContext = window.webkitOfflineAudioContext;
}
//var context = new AudioContext();
var length = 15241583;
var samplerate = 44100;
var fftSamples = 2048;
var waveformWidth = 1920;
var context = new OfflineAudioContext(1,length,samplerate);
var source;
var splitter;
var analyser;
var processor;
var i=0;
var average;
var max;
var coord;
processor = context.createScriptProcessor(fftSamples, 1, 1);
processor.connect(context.destination);
analyser = context.createAnalyser();
analyser.smoothingTimeConstant = 0;
analyser.fftSize = fftSamples;
source = context.createBufferSource();
splitter = context.createChannelSplitter();
source.connect(splitter);
splitter.connect(analyser,0,0);
analyser.connect(processor);
context.oncomplete = function(){
$('#output').append('<br />complete');
}
var request = new XMLHttpRequest();
request.open('GET', "http://www.mindthepressure.org/bounce.ogg", true);
request.responseType = 'arraybuffer';
request.onload = function(){
$('#output').append('loaded ! ');
context.decodeAudioData(request.response, function(buffer) {
$('#output').append('starting analysis<br />');
processor.onaudioprocess = function(e){
var data = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(data);
average = getAverageVolume(data);
max = Math.max.apply(Math, data);
coord = Math.min(average*2,255);
coord = Math.round((max+coord)/2);
ctx.fillStyle=gradient;
ctx.fillRect(i,255-coord,1,255);
console.log(i+' -> '+coord);
i++;
}
source.buffer = buffer;
source.start(0);
context.startRendering();
}, onError);
}
request.send();
function onError(e) {
$('#output').append('error, check the console');
console.log(e);
}
function getAverageVolume(array) {
var values = 0;
var average;
var length = array.length;
for (var k = 0; k < length; k++) {
values += array[k];
}
average = values / length;
return average;
}
(here is another version that forces waveform to fit in 1920px wide and generate a waveform data for who is interested : http://jsfiddle.net/bestiole/E3rSx/ )
i really dont get the point, how doesn't chrome treat every part of the audio file ?
thanks for any help !
Chrome has a bug in script processors in offline mode.
The following code should be able to save and load .png image to/from local hard drive.
Saving works fine(at least in chrome) but loading produces wrong url and display nothing..
A little help would be really appreciated!
<html>
<head>
<title></title>
</head>
<body>
<img id="img" /><br>
<input type="button" value="Save" onclick="onSave()" /><br />
<input type="file" onchange="onOpen(event)" /><br />
<script>
onSave = function () {
var canvas = document.createElement("canvas");
canvas.width = 200;
canvas.height = 200;
var ctx = canvas.getContext("2d");
ctx.fillRect(0, 0, 100, 150);
var dataURL = canvas.toDataURL("image/png");
var img64 = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
var binaryImg = atob(img64);
var length = binaryImg.length;
var ab = new ArrayBuffer(length);
var ua = new Uint8Array(ab);
for (var i = 0; i < length; i++) {
ua[i] = binaryImg.charCodeAt(i);
}
var blob = new Blob([ab]);
var a = document.createElement("a");
a.download = 'Blob_img';
a.innerHTML = "Download File";
a.href = window.webkitURL.createObjectURL(blob);
a.style.display = 'none';
document.body.appendChild(a);
a.click();
};
onOpen = function (event) {
var fileReader = new FileReader();
fileReader.onload = function (event) {
var ab = event.target.result;
var ua = new Uint8Array(ab);
var binaryImg;
for (var i = 0; i < ua.length; i++) {
binaryImg += String.fromCharCode(ua[i]);
}
var img64 = btoa(binaryImg);
var image = new Image();
image.src = 'data:image/png;base64,' + img64;
var img = document.getElementById('img');
img.src = image.src;
}
fileReader.readAsArrayBuffer(event.target.files[0]);
};
</script>
</body>
</html>
Your "load" handler for your FileReader is declared without an event parameter. As a result, it's not going to have access to the file contents.
fileReader.onload = function (event) {
var ab = event.target.result;
Without that parameter, the symbol "event" would refer to the parameter of the enclosing function, and that one won't have the file contents.
Also, I think you don't need to do the base64 encoding/decoding via atob and btoa, because the results of converting the canvas contents to a data URL will be a base64 string anyway.
In case somebody is wondering, there is a simpler way of reading the file:
FileReader.readAsDataURL
Check a working example at https://developer.mozilla.org/en-US/docs/Web/API/FileReader.readAsDataURL.