Setting local image as EaselJS background - html

I am building an EaselJS app, and I want the user to be able to select an image from their hard drive to be the background for the app. Once they are done interacting with the app and choose to submit I want to upload the image, but not before then. Is there a way I can do this? I am using Rails if that makes any difference.

You can use the method readAsDataURL from Filereader,then pass the result to an Image object and finally pass that image as parameter of a new easeljs.Bitmap object.
function previewFile(){
var file = input.files[0];
var reader = new FileReader();
reader.onloadend = function () {
image.src = reader.result;
var bitmap = new createjs.Bitmap(image);
stage.addChild(bitmap);
}
if (file) {
reader.readAsDataURL(file);
} else {
alert("fail");
}
}
I created a fiddle that does something like that:
https://jsfiddle.net/vampaynani/b5maj7nd/

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

Crop an Image in nokia Imaging SDK 1.2?

Can you give me a sample code for crop an Image using Nokia Imaging SDK 1.2 ? As you know the "Editing Session" class, that I use for cropping Image has gone in SDK 1.2.
Thanks for your attention.
This is an excerpt from the nokia api reference documentation which can be found here:
http://developer.nokia.com/resources/library/Imaging_API_Ref/nokiagraphicsimaging-namespace/cropfilter-class.html
This sample takes CameraCaptureTask result photo and applies a [crop] filter to it.
async void CaptureTask_Completed(object sender, PhotoResult e)
{
// Create a source to read the image from PhotoResult stream
using (var source = new StreamImageSource(e.ChosenPhoto))
{
// Create effect collection with the source stream
using (var filters = new FilterEffect(source))
{
// Initialize the filter
var sampleFilter = new CropFilter(new Windows.Foundation.Rect(0, 0, 500, 500));
// Add the filter to the FilterEffect collection
filters.Filters = new IFilter[] { sampleFilter };
// Create a target where the filtered image will be rendered to
var target = new WriteableBitmap((int)ImageControl.ActualWidth, (int)ImageControl.ActualHeight);
// Create a new renderer which outputs WriteableBitmaps
using (var renderer = new WriteableBitmapRenderer(filters, target))
{
// Render the image with the filter(s)
await renderer.RenderAsync();
// Set the output image to Image control as a source
ImageControl.Source = target;
}
}
}
}

How can I paste an image from the clipboard onto a Canvas element using Dart?

I'm using Dart to develop a personal whiteboard Chrome app and it is sometimes useful to be able to quickly copy and paste an image (e.g. a slide from a presentation, a diagram or a handout) so that I can add notes over the image while teaching a class or giving a presentation.
How can I paste an image stored on the clipboard onto a canvas element in Dart?
Actually, this answer to the same question for JS is almost directly applicable. A Dart translation might look something like:
import 'dart:html';
void main() {
var can = new CanvasElement()
..width = 600
..height = 600
;
var con = can.getContext('2d');
document.onPaste.listen((e) {
var blob = e.clipboardData.items[0].getAsFile();
var reader = new FileReader();
reader.onLoad.listen((e) {
var img = new ImageElement()
..src = (e.target as FileReader).result;
img.onLoad.listen((_) {
con.drawImage(img, 0, 0);
});
});
reader.readAsDataUrl(blob);
});
document.body.children.add(can);
}

In HTML5 is there any way to make Filereader's readAsBinaryString() synchronous

How to wait till onload event completes
function(){
var filedata=null;
reader.onload=function(e){
filedata=e.target.result;
};
reader.readAsBinaryString(file);
//I need code to wait till onload event handler gets completed.
return filedata;
}
Typical solution to this is to separate your code so, that the part which uses the loaded data is in a separate function, which is then called from the event.
Pseudo-code'ish:
function load() {
//load here
reader.onload = function(e) {
process(e.target.result);
}
}
function process(result) {
//finish working here
}
You can read synchronously using threads (Webworkers in Javascript).
http://www.w3.org/TR/FileAPI/#readingOnThreads
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<form><input type="file" id="files" name="file" onchange="upload()" /></form>
function readFile(dfd) {
bytes = [];
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
var content = evt.target.result;
//bytes = stringToBytes(content);
dfd.resolve(content);
}
};
reader.readAsBinaryString(file);
}
function upload() {
var dfd = new $.Deferred();
readFile(dfd);
dfd.done(function(content){
alert("content:" + content);
});
}
The answer by Jani is correct, but in the case of dropping multiple files at once in a droparea, there are not separate events for each file (as far as I know). But the idea may be used to load the files synchronously by recursion.
In the code below I load at number of files and concatenate their content into a single string for further proccesing.
var txt="", files=[];
function FileSelectHandler(e) {
e.preventDefault();
files = e.target.files || e.dataTransfer.files;
txt="";
readFile(0);
}
function readFile(n) {
file=files[n];
var reader = new FileReader();
reader.onload = function() {
txt += reader.result;
}
reader.readAsText(file);
if (n<files.length-1) { readFile(n+1); }
else { setTimeout(doWhatEver, 100);}
}
function doWhatEver(){
outtext.innerHTML=txt;
}
The last file also needs a bit of extra time to load. Hence the "setTimeout".
"outtext" is the handle to a textarea where the entire string is displayed. When outputting in at textarea the browser wont' parse the string. This makes it possible to view not only text but also html, xml etc.
No there is not. All IO operations must be asynchronous in Javascript.
Making file operation synchronous would effectively block the browser UI thread freezing the browser. The users don't like that.
Instead you need to design your script in asynchronous manner. It is quite easy with Javascript.