context.getImageData() on localhost? - html

I have the following snippet of code and I'm trying to run it from localhost (OSX, running XAMPP):
var canvas = document.getElementById('mycanvas');
var cx = canvas.getContext('2d');
var myImg = new Image();
myImg.src = 'images/lion.jpg';
$(myImg).load(function() {
cx.drawImage(myImg, 0, 0);
var imgData = cx.getImageData(0,0,150,150);
});
But when I run it I get this error from the console:
Unable to get image data from canvas because the canvas has been tainted by cross-origin data.
site.js:11Uncaught Error: SECURITY_ERR: DOM Exception 18
I found some similar questions here and I know that this has something to do with the fact that I'm working locally and this wouldn't happen if I was trying to access the image from the same domain. I don't know if this makes sense, but it's what I understood.
My question is, how can I make this work in a local dev environment?

Serve your html with an HTTP server, for example, Apache or Nginx.
Mac OSX comes with Python installed, so you can simply start an HTTP server by opening a terminal, then input:
cd /path/to/my/work/
python -m SimpleHTTPServer
Then open http://localhost:8000/ in your browser. This should work.

Trying a different browser might help. This happened to me on Chromium and just by switching to Firefox I was able to continue debugging locally.

I ended up using a combo of solutions (see this other problem)
Steps:
Transform the image to base64 string.
Assign that as the src of the Image js object.
Draw on canvas
Code:
// helper to transform to base64
// see other question for more help
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
}
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
var png = new Image();
var backgroundSrc = ".....";
png.onload = function () {
ctx.drawImage(png, 0, 0);
};
toDataUrl(backgroundSrc, function(base64Img) {
png.src = base64Img;
});
I know this solution is NOT optimal, but it worked for me AND it helps when the image does not come from the same origin.
I'm posting this for anyone that encounters the same problem.

Related

Download canvas as image with button

What is the id of this canvas: carstenschaefer.github.io/DrawerJs/examples/fullscreen I want to add download button to under this canvas. I imported the source code into vscode. I tried various download codes but none of them worked. I think I'm writing the id wrong.
document.getElementById('download').addEventListener('click', ()=> {
var canva = document.getElementById("canvas");
var image = canva.toDataURL("image/png").replace("image/png", "image/octet-stream");
var element = document.createElement('a');
var filename = 'test.png';
element.setAttribute('href', image);
element.setAttribute('download', filename);
element.click();
})
When you create an instance of drawer
const drawer = new DrawerJs.Drawer(null, { ...options });
You can call
drawer.api.getCanvasAsImage()
To get the canvas converted to base64 which you can then use it to Post to a backend server or download it.
Took at look at download.js maybe you could try using it to help with saving.

Adding static image to Lightswitch HTML 2013 Browse Screen

In my case, I have color coded some tiles in the HTML client and I want to add a simple color code key. I have the PNG file I want to use.
I do not require the ability to upload or change the image.
This link seems to achieve what I am looking for, but I am not sure where to implement. Does all of this code go into the PostRender of the Image Control I created?
Add image to lightswitch using local property and file location
Here is what the PostRender of the simple Image data item I created as an Image Local Property, and then dragged into the Solution Designer. It was basically copied from the link above, but I did change the name of the image file to match mine, and I have already added the item to the Content\Images folder structure and it shows in the file view:
myapp.BrowseOrderLines.ColorKey_postRender = function (element, contentItem) {
// Write code here.
function GetImageProperty(operation) {
var image = new Image();
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
// XMLHttpRequest used to allow external cross-domain resources to be processed using the canvas.
// unlike crossOrigin = "Anonymous", XMLHttpRequest works in IE10 (important for LightSwitch)
// still requires the appropriate server-side ACAO header (see https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image)
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var url = URL.createObjectURL(this.response);
image.onload = function () {
URL.revokeObjectURL(url);
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0);
var dataURL = canvas.toDataURL("image/png");
operation.complete(dataURL.substring(dataURL.indexOf(",") + 1));
};
image.src = url;
};
xhr.open('GET', this.imageSource, true);
xhr.responseType = 'blob';
xhr.send();
};
myapp.BrowseOrderLines.ColorKey_postRender = function (element, contentItem) {
// Write code here.
msls.promiseOperation
(
$.proxy(
GetImageProperty,
{ imageSource: "content/images/Key.png" }
)
).then(
function (result) {
contentItem.screen.ImageProperty = result;
}
);
};
}
Currently, the Image control does show on the screen in the browser, and is the custom size I choose, but it is just a light blue area that does not display my image file.
I am not sure if I have embedded the image? I am not sure if that is a missing step?
Thank you!!
The easiest method of testing this approach would be to change your postRender to the following (which embeds the helper function within the postRender function):
myapp.BrowseOrderLines.ColorKey_postRender = function (element, contentItem) {
function GetImageProperty(imageSource) {
return msls.promiseOperation(
function (operation) {
var image = new Image();
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
// XMLHttpRequest used to allow external cross-domain resources to be processed using the canvas.
// unlike crossOrigin = "Anonymous", XMLHttpRequest works in IE10 (important for LightSwitch)
// still requires the appropriate server-side ACAO header (see https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image)
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var url = URL.createObjectURL(this.response);
image.onload = function () {
URL.revokeObjectURL(url);
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0);
var dataURL = canvas.toDataURL("image/png");
operation.complete(dataURL.substring(dataURL.indexOf(",") + 1));
};
image.onerror = function () {
operation.error("Image load error");
};
image.src = url;
};
xhr.open('GET', imageSource, true);
xhr.responseType = 'blob';
xhr.send();
}
);
};
GetImageProperty("content/images/Key.png").then(function onComplete(result) {
contentItem.screen.ImageProperty = result;
}, function onError(error) {
msls.showMessageBox(error);
});
};
This assumes that you named the local property ImageProperty as per my original post and the Image control on your screen is named ColorKey.
In the above example, I've also taken the opportunity to slightly simplify and improve the code from my original post. It also includes a simple error handler which may flag up if there is a problem with loading the image.
If this still doesn't work, you could test the process by changing the image source file-name to content/images/user-splash-screen.png (this png file should have been added as a matter of course when you created your LightSwitch HTML project).
As the GetImageProperty function is a helper routine, rather than embedding it within the postRender you'd normally place it within a JavaScript helper module. This will allow it to be easily reused without repeating the function's code. If you don't already have such a library and you're interested in implementing one, the following post covers some of details involved in doing this:
Lightswitch HTML global JS file to pass variable

Changing the pitch of the sound of an HTML5 audio node

I would like to change the pitch of a sound file using the HTML 5 Audio node.
I had a suggestion to use the setVelocity property and I have found this is a function of the Panner Node
I have the following code in which I have tried changing the call parameters, but with no discernible result.
Does anyone have any ideas, please?
I have the folowing code:
var gAudioContext = new AudioContext()
var gAudioBuffer;
var playAudioFile = function (gAudioBuffer) {
var panner = gAudioContext.createPanner();
gAudioContext.listener.dopplerFactor = 1000
source.connect(panner);
panner.setVelocity(0,2000,0);
panner.connect(gainNode);
gainNode.connect(gAudioContext.destination);
gainNode.gain.value = 0.5
source.start(0); // Play sound
};
var loadAudioFile = (function (url) {
var request = new XMLHttpRequest();
request.open('get', 'Sounds/English.wav', true);
request.responseType = 'arraybuffer';
request.onload = function () {
gAudioContext.decodeAudioData(request.response,
function(incomingBuffer) {
playAudioFile(incomingBuffer);
}
);
};
request.send();
}());
I'm trying to achieve something similar and I also failed at using PannerNode.setVelocity().
One working technique I found is by using the following package (example included in the README): https://www.npmjs.com/package/soundbank-pitch-shift
It is also possible with a biquad filter, available natively. See an example here: http://codepen.io/qur2/pen/emVQwW
I didn't find a simple sound to make it obvious (CORS restriction with ajax loading).
You can read more at http://chimera.labs.oreilly.com/books/1234000001552/ch04.html and https://developer.mozilla.org/en-US/docs/Web/API/BiquadFilterNode.
Hope this helps!

How to test html canvas experiments on Chrome locally

I wrote a simple canvas demo program but it doesn't seem to produce the required result.
Here is my code:-
window.onload = function(){
var canv = document.getElementById('canv');
var cxt = canv.getContext('2d');
if(cxt){
var myimg = document.getElementById('mypic');
setTimeout(function(){
cxt.drawImage(myimg,0,0,canv.width,canv.height);
var edit = cxt.getImageData(0,0,canv.width,canv.height);
var imgdata = edit.data;
for(var i=0;i<imgdata.length;i+=4){
imgdata[i] = 255;
imgdata[i++] = 255;
imgdata[i+3] = 127;
}
cxt.putImageData(imgdata,0,0);
}
,100);
$('<p>Canvas Created</p>').appendTo('body');
}
};
Most likely one of two things is going wrong.
You are not waiting for your image to finish loading which might be a problem.
Or you are running in to a security exception. Calling getImageData is now allowed if an image has been loaded on to the canvas from an outside source. Your hard-drive constitutes an outside source, even if you are running locally. To see if this is the case I'd suggest debugging in FireFox because its web console will actually tell you about this security error.

Send Image File via XHR on Chrome

I'm using HTML5 drag&drop to get images from a user's computer and want to upload them to my Rails server (using Carrierwave on that end). I don't know exactly what I'm doing here, but cobbled together this code from these instructions http://code.google.com/p/html5uploader/wiki/HTML5Uploader
This returns a 500 error - can anyone take a look and help me out with what I'm doing wrong?
var files = e.dataTransfer.files;
if (files.length){
for (var i = 0; i<files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function() {
var bin = reader.result;
var xhr = new XMLHttpRequest();
var boundary = 'xxxxxxxxx';
xhr.open('POST', '/images?up=true&base64=true', true);
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
xhr.setRequestHeader('UP-FILENAME', file.name);
xhr.setRequestHeader('UP-SIZE', file.size);
xhr.setRequestHeader('UP-TYPE', file.type);
xhr.send(window.btoa(bin));
};
};
};
There are a couple of things that could be the culprit. You're reading the file as a binary string, then creating a multipart request, then sending a base64 encoded value.
There's no need to read the file or mess with base64 encoding. Instead, just construct a FormData object, append the file, and send that directly using xhr.send(formData). See my response here.