External script not working in PaperJS v0.9.22 - javascript

I am new to paperJS and I'm trying to include an external paperscript file in html, but it isn't working. While the inline scripting is working fine. My code are:
HTML Code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/paper.js"></script>
</head>
<body>
<script type="text/paperscript" src = "js/myScript.js" canvas = "myCanvas" >
</script>
<canvas id="myCanvas" resize></canvas>
paperScript Code (myScript.js):
// Create a Paper.js Path to draw a line into it:
var path = new Path();
// Give the stroke a color
path.strokeColor = 'black';
var start = new Point(100, 100);
// Move to start and draw a line from there
path.moveTo(start);
// Note the plus operator on Point objects.
// PaperScript does that for us, and much more!
path.lineTo(start + [ 100, -50 ]);
I found an old link on stackOverflow which says that using version 0.9.10 fix the problem. But is that issue still not fixed in newer version?
Here's the link:
How to use paperscript from external source?

This is not paperJs issue. Here I was trying to load a resource from the local file system, which chrome doesn't permit (Violation of its same-origin policy) and so we need a local web server.Why?
Local web server can be setup using WAMP (on Windows), MAMP (on OS X), LAMP(for ubuntu). It can aslo be setup by Python http-server and NodeJS http-server.

The only guess I can make based on the information here is that you're loading paper-core.js, not paper-full.js. paperscript is not implemented in paper-core.js.
The behavior if it's paper-core.js would be that your code is never called because there is nothing to interpret paperscript.

Actually I found the solution via another student in Udemy -Git link here. Go to the paper-full.js (it works only with the downloaded version, not CDN) and transform the line
xhr.open((options.method || 'get').toUpperCase(), options.url,
Base.pick(options.async, true));
into only
xhr.open((options.method || 'get').toUpperCase(), options.url);
I understood that's not to be used in normal website as it's against a security protocols, so it's just for practicing. The async method is optional according to Paperjs. By the way, for me it works on Firefox, but not in Chrome.

Related

How to make GitHub Pages Markdown support mermaid diagram?

I am hoping to use mermaid in GitHub-pages, with simple commit and push.
In other words, I am hoping to wirte in my markdown file like this
```mermaid
graph LR
A --> B
A -->C
C -->D
```
and add some js on my _layouts/post.html to somehow transform this to a mermaid graph.
I have found this theme claims that it supports such thing. But this theme looks way too heavy for me, the js were just too much, so I thought I could only use this file, which is simply
<script>
window.Lazyload.js('{{ _sources.mermaid }}', function() {
mermaid.initialize({
startOnLoad: true
});
mermaid.init(undefined, '.language-mermaid');
});
</script>
In my _include/mermaid.html, I replaced {{ _sources.mermaid }} to the mermaid cdn
<script>
window.Lazyload.js('https://cdnjs.cloudflare.com/ajax/libs/mermaid/8.0.0/mermaid.min.js', function() {
mermaid.initialize({
startOnLoad: true
});
mermaid.init(undefined, '.language-mermaid');
});
</script>
it still won't work. In my post, it was shown as regular code blocks, not a mermaid diagram.
Edit: In chrome developer's view, I don't see any connections made to the link https://cdnjs.cloudflare.com/ajax/libs/mermaid/8.0.0/mermaid.min.js.
And I tried this code, a connection to mermaid wes made in network tag in developer view, but the mermaid diagram still doesn't work
<script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/8.0.0/mermaid.min.js"></script>
<script>
var config = {
startOnReady:true,
theme: 'forest',
flowchart:{
useMaxWidth:false,
htmlLabels:true
}
};
mermaid.initialize(config);
mermaid.init(undefined, '.language-mermaid');
</script>
I found the solution.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/8.0.0/mermaid.min.js"></script>
</head>
<body>
<pre><code class="language-mermaid">graph LR
A-->B
</code></pre>
<div class="mermaid">graph LR
A-->B
</div>
</body>
<script>
var config = {
startOnLoad:true,
theme: 'forest',
flowchart:{
useMaxWidth:false,
htmlLabels:true
}
};
mermaid.initialize(config);
window.mermaid.init(undefined, document.querySelectorAll('.language-mermaid'));
</script>
</html>
If you're using Jekyll, and you don't mind to use a plugin, I think the below can help you do it easier.
jekyll-spaceship - 🚀 A Jekyll plugin to provide powerful supports for table, mathjax, plantuml, mermaid, youtube, emoji, vimeo, dailymotion, etc.
https://github.com/jeffreytse/jekyll-spaceship
There are two ways to create a diagram in your Jekyll blog page:
```mermaid!
pie title Pets adopted by volunteers
"Dogs" : 386
"Cats" : 85
"Rats" : 35
```
or
#startmermaid
pie title Pets adopted by volunteers
"Dogs" : 386
"Cats" : 85
"Rats" : 35
#endmermaid
Code above would be parsed as:
Feb. 2022: Markdown pages support Mermaid (gist too) (aug. 2022: wiki pages too).
As Jegors ÄŒemisovs adds in the comments, this does not apply yet to GitHub pages, as illustrated by his example site.
See:
Include diagrams in your Markdown files with Mermaid
Mermaid is a JavaScript based diagramming and charting tool that takes Markdown-inspired text definitions and creates diagrams dynamically in the browser. Maintained by Knut Sveidqvist, it supports a bunch of different common diagram types for software projects, including flowcharts, UML, Git graphs, user journey diagrams, and even the dreaded Gantt chart.
Working with Knut and also the wider community at CommonMark, we’ve rolled out a change that will allow you to create graphs inline using Mermaid syntax:
I solved it buy installing Github Mermaid extensioin in the browser.
Actually, they have support for Chrome, Opera & Firefox.
I am using Chrome: https://chrome.google.com/webstore/detail/github-%20-mermaid/goiiopgdnkogdbjmncgedmgpoajilohe?hl=en
In addition to the other answer that mention the plugins. In a firm I work form asked to provide extention links to most supported browsers.
Here are the Mermaid extention that renders Mermaid on browser level, I have tested them all:
Mermaid diagram for documentation
When you use mermaid to create diagrams in Gitlab, and in case the business moves with new Version Control provider like Github or Azure DevOps or others, in this case you need to install a browser plugins to make it possible to view the diagrams.
Chrome -> GitHub + Mermaid
Firefox -> GitHub + Mermaid
Opera -> Extensions for Mermaid
Edge -> Extensions for Mermaid
I assume this requirement is with Jekyll + Github Pages since Github Pages is mentioned.
There's plugins doing this, such as jekyll-spaceship.
It supports a lot more rendering format.
In order to make the unsafe plugins works on Github Pages, you will need a Github Workflow Action jekyll-deploy-action.
BTW: The custom plugins (putting plugins in your _plugins folder) won't work with Github Pages, they are not the safe plugins. Github Pages locks the config to safe=true, even locally.
The URL you tried to use does not exist. This is a correct URL:
https://cdnjs.cloudflare.com/ajax/libs/mermaid/8.0.0/mermaid.min.js
I was having a similar problem and ended up just going with a custom jekyll plugin. If you are able to use custom plugins, the following will replace the markdown code blocks for mermaid with elements.
Jekyll::Hooks.register :posts, :pre_render do |post, payload|
docExt = post.extname.tr('.', '')
# only process if we deal with a markdown file
if payload['site']['markdown_ext'].include? docExt
newContent = post.content.gsub(/```mermaid([^`]+?)```/, '<div class="mermaid">\1</div>')
post.content = newContent
end
end
The new best answer is that GitHub now directly supports including diagrams in your markdown files with Mermaid!
https://github.blog/2022-02-14-include-diagrams-markdown-files-mermaid/

HTML/JS github pages project doesn't load images or sounds when run with firefox

Alright so this is a weird one, I'm not entirely sure if this is the right SE site, but I think it is because it regards web code/browser compatibility. If not, someone tell me in the comments I'll move it.
So basically, I have my game's source code on github. I also am hosting the game itself on github pages. This game should (I believe) function on Firefox and Chrome browsers. The source code has nothing unique to either browser.
The game runs fine on chrome. However, on Firefox this is not the case. None of the assets (images, sounds) are showing up/working on the github pages link. The weird thing is this though: on my local file system, when I open the html file with FF it runs/renders the assets just fine. Also, when I download the zip of my project and try it w/ FF, it also works fine. Why is this the case?
(Note, if you want to see the problem, click on the github pages link, then click on "Start Game", this will open it up to the game where the problem is occuring)
Edit:
Forgot to mention, the error I get in the FF console is NS_ERROR_NOT_AVAILABLE: it leads to line 421 which is this: g2d.drawImage(playerSprite, spriteLoc[0], spriteLoc[1]); where I draw the image onto the canvas. g2d is supposed to be ctx btw, thats a bad java habbit.
try changing the path of the resources.
you call the sound files, and image files this way:
laserSound = new Audio("resources\\Sounds\\laserblast.wav");
playerSprite.src = "resources\\Sprites\\Sprite.png";
you need to change the path to this:
laserSound = new Audio("resources/Sounds/laserblast.wav");
playerSprite.src = "resources/Sprites/Sprite.png";
that is change this \ to this /
the current way you are getting it, Firefox does not find where you files are at.
also, why dont you put init(); at the bottom of the JS file, its just to make sure, that the JS parser already knows that certain functions you will be calling are defined, like update() and initBackground() (this does not seem to be a problem, but just to be on the safe side.)

Exporting a Processing Application to Web Processing IDE

I am working with Processing trying to develop a simple data visualization application for the number of people with Health Insurance in the US.
I have the sketch working locally on my machine but I have tried to export it for the web using the Javascript mode available from within the Processing IDE.
A folder is generated with a number of files including a HTML page and the JS file for the sketch. However I am getting this error when I try to load the page from my LocalHost
Uncaught Processing.js: Unable to execute pjs sketch: ReferenceError: ListstateMarkers is not defined
My entire code for my Sketch (in Java) is here:
UnfoldingMap map;
List<Marker>stateMarkers;
List<Feature>states;
void setup() {
size(800, 600);
smooth();
map = new UnfoldingMap(this);
MapUtils.createDefaultEventDispatcher(this, map);
states = GeoJSONReader.loadData(this, "ushealthinsurance2005.json");
stateMarkers = MapUtils.createSimpleMarkers(states);
stateMarkers = MapUtils.createSimpleMarkers(states);
map.addMarkers(stateMarkers);
}
void draw() {
map.draw();
for (int i = 0; i < stateMarkers.size(); i++) {
Marker state = stateMarkers.get(i);
//Get information when mouse over a county.
if (state.isInside(map, mouseX, mouseY)) {
state.setColor(color(255, 0, 0));
}
else {
state.setColor(color(0, 0, 255));
}
}
}
I should point out I am also using a Maps Library Unfolding to generate the Map tiles and add interactivity to the application.
Has anyone any Idea what might be going on here? Is this a glitch with the IDE itself? Has anyone ran into a similar problem?
The line throwing the error from within the JS file is this one:
throw "Processing.js: Unable to execute pjs sketch: " + e;
There are over 10,000 lines of generated code making it very difficult to actually debug the problem.
Appreciate any advice or help on the issue.
You can't use Java libraries in JavaScript, so you can't use them in Processing.js.
You have three options:
Option 1: Find a JavaScript library that does the same thing. Unfortunately, Unfolding Maps does not support JavaScript, so you'll have to use something else. The GoogleMaps API might be worth checking out. If you want to embed your application in a website, this is the only real option.
Option 2: Deploy as a runnable jar. You can use something like JarMatey (note: I wrote JarMatey) to package your Processing sketch as a self-extracting runnable jar. You won't be able to embed this in a webpage, but you might use Java Web Start to make deploying over the web easier.
Option 3: Deploy as a packaged executable. Processing can export applications, but they require library directories instead of coming as a single file. Instead, you can create a runnable jar and then use something like JWrapper to create a single-file executable.
Note: Deploying as an applet isn't really an option. Applets are pretty much dead, and they'll be a huge pain for both you and your users. Applets will be deprecated in Java 9.

A cross-browser alternative to Canvas2Image or HTML5 download attribute?

While developing a pattern generator I am running into the same problem described in this question from 2011.
The answers given don't really offer a cross-browser, client-side solution.
I would accept any of the following solutions when clicking the Export Pattern button:
Triggering a download through canvas2image while ensuring that the file is saved with a .png extension (no matter what the filename is set to) or,
Display a widget (KendoUI preferably) with the image resulting from the Canvas2Image.saveAsPNG() method and let the user save it from there preferably not using the lame right-click solution, but with a link or a button.
HTML for the button I'm currently using:
<button id="downloadbtn" onClick="javascript:downloadImage()" data-role="button" class="k-button">Export Pattern</button>
Function that triggers the download:
function downloadImage () {
//...extra code omitted
var oCanvas = document.getElementById("my_canvas");
oCanvas.width = $("#pixels-h").val();
oCanvas.height = $("#pixels-v").val();
Canvas2Image.saveAsPNG(oCanvas);
//...extra code omitted
}
The file seems to download fine under OSX with Chrome Version 23.0.1271.95 and Safari Version 5.1.7 (6534.57.2).
I have a report of someone unable to open the file after downloading it under Firefox 17.0.1 for OSX. Apparently the download generates a .part file.
The biggest issue is that without a file extension I doubt that this method can be reliable.
I am looking for a client-side only solution with the widest possible compatibility with current browsers, so I guess the HTML5 download attribute would not do the trick as it is currently only supported in Chrome.
Any creative solutions?
I ran into the same issue. The basic problem is the filename needs to be added in the header but canvas2images uses document.location.href = strData and strData doesnt have headers. So the answer is, canvas2image does not support the feature we need, and we will need to try another solution. (for example perhaps FileSaver.js and canvas-toBlob.js)
http://eligrey.com/demos/FileSaver.js/

Embedding image in QWebView with JavaScript

I am writing a small application with Qt 4.6 (64-bit Arch Linux, though that shouldn't matter) which lets the user edit a document using a QWebView with contentEditable turned on. However, for some reason embedding an image does not work. Here is a code snippet:
void LeafEditView::onInsertImage()
{
// bring up a dialog, ask for an image
QString imagePath = QFileDialog::getOpenFileName(this,tr("Open Image File"),"/",tr("Images (*.png *.xpm *.jpg)"));
ui->leafEditor->page()->mainFrame()->documentElement().evaluateJavaScript("document.execCommand('insertImage',null,'"+imagePath+"');");
}
The test image does in fact exist and yet absolutely nothing happens. Bold / italics / underline all work fine via JavaScript, just not images. Thoughts?
Check that QWebSettings::AutoLoadImages is enabled.
You could also try:
document.execCommand('insertImage',false,'"+imagePath+"');
Try using relative vs absolute paths to the image.
Last but not least, poke around this sample application -- they are using a similar method of Javascript execCommand(), they do some things in a slightly different way such as using QUrl::fromLocalFile.
Best of luck!
It turns out that WebKit has a policy of not loading resources from the local filesystem without some massaging. In my code, I have a WebKit view which I'm using to edit leaves in a notebook. The following one-liner solved my issue:
ui->leafEditor->page()->mainFrame()->setHtml("<html><head></head><body></body></html>",QUrl("file:///"));
From what I gleaned by lurking around the WebKit mailing list archives, in order to load files from the local filesystem one must set the URI to be file:, and this does the job.

Categories