How to Upload and load image in Konvajs canvas? - vue.js

I have used konva js plugin for canvas representation. I have gone through the document, but can't get any help to upload the image using konvajs.
Is it so that I need to do custom code? Does konva js support image upload from folder and save to canvas elements?
How upload/store external image is managed?

Your question is really about how to let the user select an image and get that displayed in an img element in the browser. Once the img element is loaded you can use that to draw in to a Konva.Image element.
I adapted the code from this question which shows how to load a local image into an HTML img element - then modified it to load the image into a Konva image object on a canvas.
I realise this is plain JS, but you should be able to find Vue examples of loading the local image on the Internet - just use the onload event to handle the Konvajs steps.
// Create the stage and a layer to draw on.
var stage = new Konva.Stage({
container: 'canvas-container',
width: 650,
height: 300
});
var layer = new Konva.Layer();
stage.add(layer);
stage.draw();
// listen for the file input change event and load the image.
$("#file_input").change(function(e){
var URL = window.webkitURL || window.URL;
var url = URL.createObjectURL(e.target.files[0]);
var img = new Image();
img.src = url;
img.onload = function() {
var img_width = img.width;
var img_height = img.height;
// calculate dimensions to get max 300px
var max = 300;
var ratio = (img_width > img_height ? (img_width / max) : (img_height / max))
// now load the Konva image
var theImg = new Konva.Image({
image: img,
x: 50,
y: 30,
width: img_width/ratio,
height: img_height/ratio,
draggable: true,
rotation: 20
});
layer.add(theImg);
layer.draw();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/konva/3.2.5/konva.min.js"></script>
<div>Render a local image without upload</div>
<div>
<input type="file" id="file_input">
</div>
<div id="canvas-container" style='display: inline-block; border: 1px solid #ccc; background-color: #ccc; overflow: auto;'></div>

Related

vue2 DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported

I am using vue2 in my project. I have an img tag which i have added crossorigin = "anonymous" to it.
I need to use canvas to print screen from a video in a specific time and show it. After I draw the image when I try to assign canvas.datatourl() to my img tag src, I get the error which you can see in title.
I searched the whole internet. All solutions were to put crossorigin="anonymous" and the problem would be solved. I tried this (as I said inside img tag or the moment before I assign canvas.datatourl() to my img tag src) but I still get this error. This is my img tag:
<img id="imgeBeforeMainVideo" class="beforeMainVideo" crossorigin="anonymous"/>
and this is my screen shot function:
var video = document.getElementById(videoId);
var w = video.videoWidth;
var h = video.videoHeight;
var canvas2 = document.createElement("canvas");
canvas2.width = w;
canvas2.height = h;
document.getElementById("imgeBeforeMainVideo").crossorigin = "anonymous";
var ctx = canvas2.getContext("2d");
ctx.drawImage(video, 0, 0, canvas2.width, canvas2.height);
let image = canvas2.toDataURL("image/jpeg")
document.getElementById("imgeBeforeMainVideo").src = image;

Selenium: Need valid image location/path of an image file placed on a website

I am able to find img tag using iwebdriver.findElement() query. Image contains captcha.
I also get the src attribute which contains the url of image but it is not working when i open it it gives me 404 error.
This is the img tag i am looking for and i need its valid image path.
{img src="https://EU1.client.hip.live.com/GetHIPData?hid=EU1.d3f00459fcb444fc8efb402f3c2dc237&fid=bbc4f6c344e7434c9b712c2d80f7268c&id=274850&type=visual&hdid=0&rnd=1798e82f1c7d4d51922f1a58c03c4d74" style="display: inline; width: 218px; height: 48px;" id="wlspispHIPBimg05f4e37f6e1bc431d8c335e2d169a0f440"}
// Assuming webdriver is set and running
IWebdriver _driver=new firefoxdriver(capabilities);
_driver.Navigate().GoToUrl("http://www.bing.com/toolbox/submit-site-url");
IWebElement img_tag = _driver.FindElement(By.CssSelector("img[style='display: inline; width: 218px; height: 48px;']"));
// Now i have the entire img tag required which contains a image.
string source_path=img_tag.GetAttribute("src");
// Now i have src url of image. but it does not show the image when i go to this source path. This is the relative path of the image i think.
I've opened the page you'r visiting. As you're trying to get captcha image. You won't be able to get image from captcha image source.
You have to get screenshot of page and crop the captcha image.
Don't use css selector with width and height. Some pages are responsive, it will put you in trouble. Use XPath instead.
public Image GetCaptchaImage()
{
Image imgCap = null;
try
{
var arrScreen = driver.GetScreenshot().AsByteArray;
using (var msScreen = new MemoryStream(arrScreen))
{
var bmpScreen = new Bitmap(msScreen);
var cap = driver.FindElement(By.XPath("//div[#id='ispHIPHIP']//img"));
var rcCrop = new Rectangle(cap.Location, cap.Size);
imgCap = bmpScreen.Clone(rcCrop, bmpScreen.PixelFormat);
}
}
catch
{
}
return imgCap;
}

How do I adjust the dojo BorderContainer layout to handle rotated buttons?

I'm trying to implement a navigation toolbar down the left side of my application with rotated buttons. When I rotate the buttons using css transform:rotate, border container still does all of its layout calculations as if the buttons were not rotated so they end up overlapping and in the wrong position vertically. Before I dig into understanding the dijit/layout/utils module well enough to solve this, I'm wondering if anyone already has a solution I'm just not seeing.
Thanks!
Fiddle here http://jsfiddle.net/eric_isakson/2bkKk/6/
JavaScript:
require(["dojo/_base/window", "dijit/Toolbar", "dijit/form/Button", "dijit/layout/BorderContainer"], function(win, Toolbar, Button, BorderContainer) {
var bc = new BorderContainer();
bc.placeAt(win.body(), "last");
var tb = new Toolbar({region: "leading"});
bc.addChild(tb);
var b1 = new Button({label: "button1"});
tb.addChild(b1);
var b2 = new Button({label: "button2"});
tb.addChild(b2);
bc.startup();
tb.startup();
b1.startup();
b2.startup();
});
CSS
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow:hidden;
}
.dijitBorderContainer {
width: 100%;
height: 100%;
}
.dijitButton {
transform:rotate(-90deg);
-ms-transform:rotate(-90deg); /* IE 9 */
-webkit-transform:rotate(-90deg); /* Safari and Chrome */
display: block;
}
Here is the desired appearance:
If i understand you right, you want your Buttons horizontal?
Then you only need to delete the rows for the rotation.
.dijitButton {
display: block;
}
Regards, Miriam

Printing PDF documents from Windows 8 App

I'm trying to print a PDF file from my Windows 8 app to connected printer. I'm coding with WinJS, and know that I have to create a print task to initiate printing from a Windows 8 app. So, after reviewing the documentation, I have this code:
onPrintTaskRequested: function (e) {
var self = Application.navigator.pageControl,
printTask = e.request.createPrintTask("Print Test Doc", function (args) {
args.setSource(MSApp.getHtmlPrintDocumentSource(document));
// Register the handler for print task completion event
printTask.oncompleted = self.onPrintTaskCompleted;
});
}
According to the documentation, the MSApp.getHhtmlPrintDocumentSource method accepts a specific set of data types. As stated in the documentation:
This can be the root document, the document in an IFrame, a document
fragment, or a SVG document. Be aware that htmlDoc must be a document,
not an element.
Apparently I cannot simply set the argument for getHtmlPrintDocumentSource to a .PDF or .PNG binary. So, I'm curious: does the WinJS library offer a method for printing so that I can implement the printing of a PDF file to a connected printer? Can anybody offer some tips to implement?
After trial and error, I was finally able implement the printing of a Base64 stream representing a PDF binary from a Windows 8 application.
I'm coding the app in HTML / CSS / WinJS. Essentially here is a brief explanation of how it was accomplished:
Create a new <canvas> element within the default.html file. Place it right after the open tag of the element. Like this:
<body role="application" class="app">
<canvas id="pdf-render-output"></canvas>
.
.
.
</body>
Then inside the default.css file, setup a few rules as well as a print media query. Like this:
body > canvas {
display: none;
}
.
. /* all your app's default css styles */
.
#media print {
body > * {
display:none;
max-width: 100%;
}
html {
max-width: 100%;
border-top-color: none;
border-top: 0;
}
body > canvas {
display: block;
border: none;
max-width: 100%;
width: 100%;
height: 100%;
position: relative;
}
}
Of note is the order in which the rules are declared in CSS. It's important to place the print media query after declaring default CSS rules.
After this is setup, javascript handles the rest. The basic idea is to render the PDF.js output to the "hidden" canvas in the DOM. When the document object gets sent to print, the CSS print media declaration is queried so that all elements under <body> are hidden except for the canvas element. Here is the javascript to print only the first page in the PDF:
//Define a container for the Base64 data we'll use with PDF.js
var pdfPrintData = {};
//Function to render PDF to canvas and begin printing contract with Windows 8 OS
printPrescription: function () {
var self = Application.navigator.pageControl,
printManager = Windows.Graphics.Printing.PrintManager.getForCurrentView();
self.getPDF().done(function () {
var pdfStream = pdfPrintData.base64,
pdfFile = convertDataURIToBinary(pdfStream);
PDFJS.disableWorker = true;
PDFJS.getDocument(pdfFile).then(function (pdf) {
var numPages = pdf.numPages,
renderCanvas = $('#pdf-render-output')[0];
//setup canvas
renderCanvas.height = pdf.getPage(1).data.getViewport(1).height;
renderCanvas.width = pdf.getPage(1).data.getViewport(1).width;
//Setup a render context for pdf.js to out a pdf file to the canvas.
var renderContext = {
canvasContext: renderCanvas.getContext('2d'),
viewport: pdf.getPage(1).data.getViewport(1)
};
//Bring up Windows 8 OS print after PDF is rendered to render context.
pdf.getPage(1).data.render(renderContext).then(function () {
printManager.onprinttaskrequested = self.onPrintTaskRequested;
Windows.Graphics.Printing.PrintManager.showPrintUIAsync();
});
})
});
},
onPrintTaskRequested: function (e) {
var self = Application.navigator.pageControl,
printTask = e.request.createPrintTask("Print Prescription", function (args) {
args.setSource(MSApp.getHtmlPrintDocumentSource(document));
printTask.oncompleted = self.onPrintTaskCompleted;
});
},
onPrintTaskCompleted: function (e) {
if (e.completion === Windows.Graphics.Printing.PrintTaskCompletion.failed) {
console.log("[ERX] : Failed to print!");
}
}
The self.getPDF method is just a function that retrieves the Base64 data stream, and that streams gets set on the .base64 property of the global pdfPrintData object. For some reason, I was not able to render the pdf using pdf.js to a dynamically create canvas in a dynamically created document. I had to render the output of the pdf.js render method to a canvas already present in the DOM.
As far as I know, MSApp.getHtmlPrintDocumentSource(document) is meant to be used with HTML document objects, and nothing else.
If you can assume Windows 8.1, you can try to assemble a new HTML document from your PDF file by exporting each page into a raster image using PdfPage.RenderToStreamAsync. There is a sample project in MSDN for a PDF viewer that uses this new API where you can learn how to use this method.
If you cannot assume Windows 8.1 and you need to support plain Windows 8 or Windows RT (ARM), you might need to use a third party library to create the raster images or to do the printing all together.
Amyuni PDF Creator for WinRT for example can do the printing for you. Disclaimer: I currently work for the company that develops the library

Dojo Tollkit - height of ScrollableView inside Dialog

I use Dojo Toolkit 1.7.2 from http://ajax.googleapis.com/ajax/libs/dojo/1.7.2/dojo/dojo.js
I need to show scrollable (with help touch) content inside dialog. Also, if possible, I will need to have transition between views inside dialog like at mobile too.
What I do (simplified version of code):
var dialog = new Dialog();
var view = new ScrollableView({
selected: true
});
//add some content inside view. Content heigh is greater than height of dialog.
If I do this, the dialog tries to fit the whole height of the content.
Next attempt:
var dialog = new Dialog({
style: {
width: 600,
height: 400
}
});
or
dialog.resize({w: 600, h: 400});
Now dialog has fixed height, but inner ScrollableView instance won't scroll to bottom of its content.
When I dig into the source, I find that ScrollableView inherits from dojox/mobile/_ScrollableMixin which inherits from dojox/mobile/scrollable.
The resize() function of dojox/mobile/scrollable uses window height in order to calculate scrolling functionality.
Is there some way to have what I need without implementating my own version of ScrollableView?
Solution:
var dialogRect = domGeometry.getMarginBox(dialog.domNode);
var headerRect = domGeometry.getMarginBox(dialog.titleBar);
var containerNodePaddingTop = domStyle.get(dialog.containerNode, "paddingTop");
var containerNodePaddingBottom = domStyle.get(dialog.containerNode, "paddingBottom");
var viewHeight = dialogRect.h - headerRect.h - containerNodePaddingTop - containerNodePaddingBottom;
var view = new ScrollableView({
selected: true,
height: viewHeight.toString() + "px"
});
// or
// view.set("height", viewHeight.toString() + "px");
Fixed it this way:
var Name = 'yourdialogid';
dojo.query("#"+Name+" .dijitDialogPaneContent").forEach(function(node, index, arr){
dojo.style(node,"overflow","auto");
dojo.style(node,"height",(dojo.position(dijit.byId(Name).domNode).h-80)+"px");
});