I took standard drawHitFromCache demo (http://www.html5canvastutorials.com/kineticjs/html5-canvas-pixel-detection-with-kineticjs/) , and replaced one of images with .svg image (gray polygon) .
live demo : http://preview.yw.sk/kineticDrawHit/
source : http://preview.yw.sk/kineticDrawHit/kineticDrawHitSvg.rar
fiddle : http://jsfiddle.net/5cpyj/ - but it will not work since of local images need.
So only thing i changed is src to svg image and added 'drawHitFromCache', it works good in chromefirefox, but in internet explorer i get :
Kinetic warning: Unable to draw hit graph from cached scene canvas. SecurityError
but i use local image (monkey.svg) no external resource, why it pops SecurityError ? Since of error image is drawn but does not react on mouse enter. With png files its all right.
jq.browser - was removed from jquery, its now as plugin to jquery , + you need canvg library fo do the magic . For canvg you need at leat 207 revision with fixed draw bug . https://code.google.com/p/canvg/source/detail?r=207 , can download latest with svn installed (http://canvg.googlecode.com/svn/trunk/)
Solution to security error in warious browsers IE10+ , Safari, Ipad etc, solution use canvg to make png images for current resolution from svg images .
var pngFallbackEnabled = null;
Project.pngFallBackCheck = function () {
if (pngFallbackEnabled == null) {
if (typeof enableSvgPngFallback != 'undefined' && enableSvgPngFallback == true && typeof jq.browser != 'undefined' && (jq.browser.mobile == true || jq.browser.msie == true || jq.browser.mozilla == true)) {
pngFallbackEnabled = true;
console.log('Png fall-back enabled');
} else {
pngFallbackEnabled = false;
}
}
return pngFallbackEnabled;
};
var cachedPngImages = [];
var currentGameCanvasRatio = null;
/** Require Canvg library*/
Project.createPngImageFromSvgImage = function (svgLink, width, height, cacheIndex) {
var extension = svgLink.split('.').pop();
if (extension == "png" || extension == "jpg" || extension == "gif" || extension == "jpeg" || extension == "gif") {
return svgLink;
}
if (typeof cacheIndex != 'undefined' && typeof cachedPngImages[cacheIndex] != 'undefined') {
return cachedPngImages[cacheIndex];
}
var canvas = document.getElementById("pngDrawerCanvas");
var canvasContext = canvas.getContext('2d');
if (canvas == null) {
var canvasElement = document.createElement('canvas');
canvasElement.setAttribute("id", "pngDrawerCanvas");
canvasElement.setAttribute("width", "200");
canvasElement.setAttribute("height", "200");
canvasElement.setAttribute("style", "display: none");
document.body.appendChild(canvasElement);
canvas = document.getElementById("pngDrawerCanvas");
}
if(currentGameCanvasRatio == null){
currentGameCanvasRatio = window.module.canvas.getCurrentRatio(); /*custom function for ratio by current screen resolution*/
}
var imageWidth = Math.floor(width * currentGameCanvasRatio);
var imageHeight = Math.floor(width * currentGameCanvasRatio);
canvas.width = imageWidth;
canvas.height = imageHeight;
jq('#pngDrawerCanvas').css('width', imageWidth);
jq('#pngDrawerCanvas').css('height', imageHeight);
//canvg('pngDrawerCanvas', svgLink, 0, 0);
canvasContext.drawSvg(svgLink, 0, 0, imageWidth, imageHeight);
var img = canvas.toDataURL("image/png");
if (typeof cacheIndex != 'undefined') {
cachedPngImages[cacheIndex] = img;
}
return img;
};
Related
I am using the following code in my event system to upload svg Images. But this gives "Parameter is not valid error" when saving the image. The following is the code I am using. Is there anything I am missing?? Any help would be really appreciated. Thanks in advance.
//only for imagaes: svg
if (mimeType.Contains("svg") && !String.IsNullOrEmpty(filename))
{
messageLog.WriteEntry("OnComponentSavePre - resizing image - for component: " + comp.Title);
// need to save first new component to be able to get type in next step
if (args.IsNewItem)
{
comp.Save();
}
BinaryContent bc = comp.BinaryContent;
var objConvertor = System.ComponentModel.TypeDescriptor.GetConverter(typeof(System.Drawing.Bitmap));
var bmpObj = (Bitmap)objConvertor.ConvertFrom(bc.GetByteArray());
//reades multimedia fields
ItemFields itemFields = new ItemFields(comp.Metadata, comp.MetadataSchema);
if (itemFields.Contains("MM_Width"))
{
NumberField width = itemFields["MM_Width"] as NumberField;
if (width != null && width.Value <= 0)
{
messageLog.WriteEntry("width = " + width.Value, EventLogEntryType.Information, 0, 0);
width.Value = bmpObj.Width;
}
}
if (itemFields.Contains("MM_Height"))
{
NumberField height = itemFields["MM_Height"] as NumberField;
if (height != null && height.Value <= 0)
{
messageLog.WriteEntry("width = " + height.Value, EventLogEntryType.Information, 0, 0);
height.Value = bmpObj.Height;
}
}
comp.Metadata = itemFields.ToXml();
messageLog.WriteEntry("metadata updated", EventLogEntryType.Information, 0, 0);
}
I have some hello world happening with leap motion using nodeJS
I want to know the pitch value for a hand, but is returning "undefined"
var Leap = require('leapjs');
var webSocket = require('ws'),
ws = new webSocket('ws://127.0.0.1:6437');
ws.on('message', function(data, flags) {
frame = JSON.parse(data);
var controller = Leap.loop(function(frame){
if(frame.hands.length == 1)
{
var hand = frame.hands[0];
var position = hand.palmPosition;
var velocity = hand.palmVelocity;
var direction = hand.direction;
var finger = hand.fingers[0];
var pitch = direction.pitch;
var type = hand.type;
if(type == "left"){
console.log("Left hand.");
console.log("pitch ::"+pitch);
}
if(type == "right") {
console.log("Right hand.")
}
}
});
if (frame.hands && frame.hands.length > 1) {
console.log("two");
}
if (frame.hands && frame.hands.length == 0) {
console.log("apaga too");
}
});
So, when i log my left hand i get
Left hand.
pitch ::undefined
I believe pitch is a method belonging to hand not direction, not an attribute belonging to direction docs. Have you tried hand.pitch() ?
I want to fix scrollbar in popUp window,but unfortunately fix it in my other pages!
Please,tell me- how to return scrollbars in Sharepoint 2010.
When i want to fix scrolls- use :
function FixRibbonAndWorkspaceDimensions() {
ULSxSy:;
g_frl = true;
var elmRibbon = GetCachedElement("s4-ribbonrow");
var elmWorkspace = GetCachedElement("s4-workspace");
var elmTitleArea = GetCachedElement("s4-titlerow");
var elmBodyTable = GetCachedElement("s4-bodyContainer");
if (!elmRibbon || !elmWorkspace || !elmBodyTable) { return; }
if (!g_setWidthInited) {
var setWidth = true;
if (elmWorkspace.className.indexOf("s4-nosetwidth") > -1)
setWidth = false;
g_setWidth = setWidth;
g_setWidthInited = true;
}
else { var setWidth = g_setWidth; }
var baseRibbonHeight = RibbonIsMinimized() ? 44 : 135;
var ribbonHeight = baseRibbonHeight + g_wpadderHeight;
if (GetCurrentEltStyle(elmRibbon, "visibility") == "hidden") { ribbonHeight = 0; }
// Override default resizing behavior
// -- adds padding to the top of the "s4-workspace" <div> if the ribbon exists and has content
// -- allows the ribbon to be positioned using CSS instead of JavaScript (more accessible)
// -- checks to see if the page is inside a "no-ribbon" dialog
var elmRibbonContainer = GetCachedElement("RibbonContainer");
if (elmRibbonContainer != null) {
if (elmRibbonContainer.children.length > 0 && document.getElementsByTagName("html")[0].className.indexOf('ms-dialog-nr') == -1) {
elmWorkspace.style.paddingTop = ribbonHeight + 'px';
}
}
}
i think ,that i have to write
I have object in SVG that I move using keyboard.
var svg = $('svg');
var avatar = svg.find('#avatar');
var left, top, right, bottom;
$(document).keydown(function(e) {
var svg = avatar[0].ownerSVGElement;
var matrix = avatar[0].getCTM();
if (e.which === 37 || left) { //left
matrix.translate(-1, 0);
e.preventDefault();
left = true;
}
if (e.which === 38 || top) { // top
matrix.translate(0, -1);
e.preventDefault();
top = true;
}
if (e.which === 39 || right) { // right
matrix.translate(1, 0);
e.preventDefault();
right = true;
}
if (e.which === 40 || bottom) { // bottom
matrix.translate(0, 1);
e.preventDefault();
bottom = true;
}
avatar.attr('transform', matrix.asString());
}).keyup(function(e) {
if (e.which === 37) {
left = false;
} else if (e.which === 38) {
top = false;
} else if (e.which === 39) {
right = false;
} else if (e.which === 40) {
bottom = false;
}
});
How can I add a trace (line that show the path of the moving avatar) in SVG? It need to be visible when I move my avatar. It would be nice if it can be not only a line but also a pattern.
I found a way, I could just put a path and add lines to it on keydown (appending it to d attribute), to simplify the path I put a line every 5 moves.
var trace;
(function() {
var start = $('#start')[0].getBBox();
var x = start.x+(start.width/2);
var y = start.y+(start.height/2);
trace = $('<path/>').attr({
id: 'trace',
stroke: '#000',
fill: 'none',
d: 'M ' + x + ' ' + y
}).appendTo(svg);
// in normal case trace path need to be added before svg is inserted to the DOM
// in my case I modify jquery library to use document.createElementNS instead of
// document.createElement
avatar.setPosition(x, y);
})();
var i = 0;
$(document).keydown(function(e) {
...
if (++i % 5 === 0) {
var avatar_size = avatar.size(); // size if jquery plugin that return width and height using BBox
var x = matrix.matrix[0][2];
var y = matrix.matrix[1][2];
trace.attr('d', trace.attr('d') + ', ' + x + ' ' + y);
}
});
I'm trying to create a simple chrome extension using the following google RSS reader sample,
http://code.google.com/chrome/extensions/samples.html#597015d3bcce3da693b02314afd607bec4f55291
I can add links in the pop-up window that open tabs, but not from the feeds themselves.
Looping through the items in the feed, grabbing title tags and link tags, I want the title to link the the appropriate sites
var entries = doc.getElementsByTagName('item');
var count = Math.min(entries.length, maxFeedItems);
for (var i = 0; i < count; i++) {
item = entries.item(i);
// Grab the title for the feed item.
var itemTitle = item.getElementsByTagName('title')[0];
if (itemTitle) {
itemTitle = itemTitle.textContent;
} else {
itemTitle = "Unknown title";
}
// Grab the link for this feed item
var itemLink = item.getElementsByTagName('link')[0];
if (itemLink) {
itemLink = itemLink.textContent;
} else {
itemLink = "Unknown link";
}
var title = document.createElement("a");
title.className = "item_title";
title.innerText = itemTitle; //display title in iframe
title.addEventListener("click", titleLink); // should open link when clicking on title, but does not.
}
// -------------------------------------------------------------------
// Show |url| in a new tab.
function showUrl(url) {
// Only allow http and https URLs.
if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
return;
}
chrome.tabs.create({url: url});
}
function moreStories(event) {
showUrl(moreStoriesUrl);
}
function titleLink(event) {
showUrl(itemLink);
}
Any thoughts on why this is not working.
If I replace title.addEventListener("click", titleLink); with title.addEventListener("click", moreStories); each title will link to moreStories, I cannot get each title to link to itemLink.
Thanks
Its a bit hard to answer your question without the whole code, but Ill give it a shot ;)
First up, titleLink() isnt going to work because itemLink isnt known. When you create title (the link) you should of attached it to that...say title.href=itemLink then in tiltleLinks you could access that href with showUrl(event.currentTarget.href)
Also did you fix the error in that example?...if not then change frameLoaded to....
function frameLoaded() {
var links = document.getElementsByTagName("A");
for (i = 0; i < links.length; i++) {
var clssName = links[i].className;
if (clssName != "item_title" && clssName != "open_box") {
links[i].addEventListener("click", showStory);
}
}
window.addEventListener("message", messageHandler);
}
If you still have probs could you attach the whole code so I can see what your doing and Ill give you a hand.
Thank you very much for your help.
code title.href=itemLink and code showUrl(event.currentTarget.href) was exactly what I needed.
For completeness, here is the full code,
<script id="iframe_script">
function reportHeight() {
var msg = JSON.stringify({type:"size", size:document.body.offsetHeight});
parent.postMessage(msg, "*");
}
function frameLoaded() {
var links = document.getElementsByTagName("A");
for (i = 0; i < links.length; i++) {
var class = links[i].className;
if (class != "item_title" && class != "open_box") {
links[i].addEventListener("click", showStory);
}
}
window.addEventListener("message", messageHandler);
}
function showStory(event) {
var href = event.currentTarget.href;
parent.postMessage(JSON.stringify({type:"show", url:href}), "*");
event.preventDefault();
}
function messageHandler(event) {
reportHeight();
}
</script>
<script>
// Feed URL.
var feedUrl = 'http://localhost/newsfeed.xml';
// The XMLHttpRequest object that tries to load and parse the feed.
var req;
function main() {
req = new XMLHttpRequest();
req.onload = handleResponse;
req.onerror = handleError;
req.open("GET", feedUrl, true);
req.send(null);
}
// Handles feed parsing errors.
function handleFeedParsingFailed(error) {
var feed = document.getElementById("feed");
feed.className = "error";
feed.innerText = "Error: " + error;
}
// Handles errors during the XMLHttpRequest.
function handleError() {
handleFeedParsingFailed('Failed to fetch RSS feed.');
}
// Handles parsing the feed data we got back from XMLHttpRequest.
function handleResponse() {
var doc = req.responseXML;
if (!doc) {
handleFeedParsingFailed("Not a valid feed.");
return;
}
buildPreview(doc);
}
// The maximum number of feed items to show in the preview.
var maxFeedItems = 10;
// Where the more stories link should navigate to.
var moreStoriesUrl;
function buildPreview(doc) {
// Get the link to the feed source.
var link = doc.getElementsByTagName("link");
var parentTag = link[0].parentNode.tagName;
if (parentTag != "item" && parentTag != "entry") {
moreStoriesUrl = link[0].textContent;
}
// Setup the title image.
var images = doc.getElementsByTagName("image");
var titleImg;
if (images.length != 0) {
var urls = images[0].getElementsByTagName("url");
if (urls.length != 0) {
titleImg = urls[0].textContent;
}
}
var img = document.getElementById("title");
// Listen for mouse and key events
if (titleImg) {
img.src = titleImg;
if (moreStoriesUrl) {
document.getElementById("title_a").addEventListener("click",moreStories);
document.getElementById("title_a").addEventListener("keydown",
function(event) {
if (event.keyCode == 13) {
moreStories(event);
}});
}
} else {
img.style.display = "none";
}
// Construct the iframe's HTML.
var iframe_src = "<!doctype html><html><head><script>" +
document.getElementById("iframe_script").textContent + "<" +
"/script></head><body onload='frameLoaded();' " +
"style='padding:0px;margin:0px;'>";
var feed = document.getElementById("feed");
// Set ARIA role indicating the feed element has a tree structure
feed.setAttribute("role", "tree");
var entries = doc.getElementsByTagName('item');
var count = Math.min(entries.length, maxFeedItems);
for (var i = 0; i < count; i++) {
item = entries.item(i);
// Grab the title for the feed item.
var itemTitle = item.getElementsByTagName('title')[0];
if (itemTitle) {
itemTitle = itemTitle.textContent;
} else {
itemTitle = "Unknown title";
}
// Grab the link for the feed item.
var itemLink = item.getElementsByTagName('link')[0];
if (itemLink) {
itemLink = itemLink.textContent;
} else {
itemLink = "Unknown link";
}
var item = document.createElement("div");
var title = document.createElement("a");
title.innerText = itemTitle; //display title in iframe
title.href=itemLink;
title.addEventListener("click", titleLink);
item.appendChild(title);
feed.appendChild(item);
}
if (moreStoriesUrl) {
var more = document.createElement("a");
more.className = "more";
more.innerText = "***Site Main Page*** \u00BB";
more.tabIndex = 0;
more.addEventListener("click", moreStories);
more.addEventListener("keydown", function(event) {
if (event.keyCode == 13) {
moreStories(event);
}});
feed.appendChild(more);
}
}
// -------------------------------------------------------------------
// Show |url| in a new tab.
function showUrl(url) {
// Only allow http and https URLs.
if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
return;
}
chrome.tabs.create({url: url});
}
// -------------------------------------------------------------------
function moreStories(event) {
showUrl(moreStoriesUrl);
}
function titleLink(event) {
showUrl(event.currentTarget.href);
}
function keyHandlerShowDesc(event) {
// Display content under heading when spacebar or right-arrow pressed
// Hide content when spacebar pressed again or left-arrow pressed
// Move to next heading when down-arrow pressed
// Move to previous heading when up-arrow pressed
if (event.keyCode == 32) {
showDesc(event);
} else if ((this.parentNode.className == "item opened") &&
(event.keyCode == 37)) {
showDesc(event);
} else if ((this.parentNode.className == "item") && (event.keyCode == 39)) {
showDesc(event);
} else if (event.keyCode == 40) {
if (this.parentNode.nextSibling) {
this.parentNode.nextSibling.children[1].focus();
}
} else if (event.keyCode == 38) {
if (this.parentNode.previousSibling) {
this.parentNode.previousSibling.children[1].focus();
}
}
}
function showDesc(event) {
var item = event.currentTarget.parentNode;
var items = document.getElementsByClassName("item");
for (var i = 0; i < items.length; i++) {
var iframe = items[i].getElementsByClassName("item_desc")[0];
if (items[i] == item && items[i].className == "item") {
items[i].className = "item opened";
iframe.contentWindow.postMessage("reportHeight", "*");
// Set the ARIA state indicating the tree item is currently expanded.
items[i].getElementsByClassName("item_title")[0].
setAttribute("aria-expanded", "true");
iframe.tabIndex = 0;
} else {
items[i].className = "item";
iframe.style.height = "0px";
// Set the ARIA state indicating the tree item is currently collapsed.
items[i].getElementsByClassName("item_title")[0].
setAttribute("aria-expanded", "false");
iframe.tabIndex = -1;
}
}
}
function iframeMessageHandler(e) {
// Only listen to messages from one of our own iframes.
var iframes = document.getElementsByTagName("IFRAME");
for (var i = 0; i < iframes.length; i++) {
if (iframes[i].contentWindow == e.source) {
var msg = JSON.parse(e.data);
if (msg) {
if (msg.type == "size") {
iframes[i].style.height = msg.size + "px";
}
else if (msg.type == "show") {
var url = msg.url;
if (url.indexOf("http://localhost/index.html") == 0) {
// If the URL is a redirect URL, strip of the destination and go to
// that directly. This is necessary because the Google news
// redirector blocks use of the redirects in this case.
var index = url.indexOf("&url=");
if (index >= 0) {
url = url.substring(index + 5);
index = url.indexOf("&");
if (index >= 0)
url = url.substring(0, index);
}
}
showUrl(url);
}
}
return;
}
}
}
window.addEventListener("message", iframeMessageHandler);
</script>
Thanks again for the help.
-Mike