So I am currently coding a game for a school project using Phaser. I am very new to Phaser and I know pretty much no JavaScript. I have looked up a lot of possible fixes online but none seem to do the trick for me. I attached my code in case I am missing something. When I change the directory of the image to an image link it works just fine but any images from my PC do not load.
var gameState = {}
function preload() {
this.load.image('monkey', 'https://vignette.wikia.nocookie.net/jungle-thick/images/0/0c/Monky.png/revision/latest?cb=20190826180942');
this.load.image('full', 'C:/Users/Public/Trash Monkey/Trash Monkey Website/Assets/Images')
;
}
function create() {
var style = {
fill: '#FFF',
font: 'Bold 32px Arial'
}
gameState.cursors = this.input.keyboard.createCursorKeys();
gameState.menuBox = this.add.rectangle(200, 250, 150, 80, 0xB5CF16);
gameState.menu = this.add.text(147.5, 231, 'START', style);
gameState.menuBox.setInteractive();
gameState.menuBox.on('pointerup', function() {
gameState.menuBox.x = 600
gameState.menu.x = 600
if(gameState.randomizer == 0) {
gameState.monkey.x = 200;
gameState.monkey.y = 0;
}
});
gameState.randomizer = Math.floor(Math.random());
if(gameState.randomizer == 0) {
gameState.monkey = this.add.sprite(2000, 0, 'monkey');
}
gameState.fullHealth = this.add.sprite(300, 37.5, 'full');
}
function update() {
if(gameState.randomizer == 0) {
gameState.monkey.y += 3;
if (gameState.cursors.right.isDown) {
gameState.monkey.x = 300;
}
if (gameState.cursors.left.isDown) {
gameState.monkey.x = 100;
}
if (gameState.cursors.up.isDown) {
gameState.monkey.x = 200;
}
if (gameState.cursors.down.isDown) {
gameState.monkey.y += 15;
}
if (gameState.monkey.y >= 500) {
gameState.monkey.y = 0;
}
}
}
var config = {
type: Phaser.AUTO,
width: 400,
height: 500,
backgroundColor: "#2191E8",
parent: 'my-game',
scene: {
preload,
create,
update
}
}
var game = new Phaser.Game(config);
You need to adjust how you are developing. The crux of the matter is that you are trying to load a file on your local computer through the browser's JavaScript context and that is plainly not allowed due to the security implications.
See:
Access to local files only work with local HTML file
The solution is to serve your project using a static server like Apache, NGINX, node.js, whatever. It doesn't matter which one. You don't need a complex solution. You just need something that will serve your work on your local machine so that you can play nice with the Browser's security concerns.
The most straightforward way to deal with the need to use a static server is to use an integrated development environment (IDE) as many will do this for you. Again it doesn't matter which one as long as it will serve your content. Eclipse and Netbeans both have project templates for static projects and are fairly easy to set up. VSCode has a Live Server extension that lets you serve a folder with just a right click.
Related
I have used jspdf and html2canvas for downloading Multiple svg into pdf format.
It is working fine in Chrome/Edge but not in Internet explorer as it shows Promise is undefined.
$("#dwnlPdf").click(function () {
downloadDocs();
});
var doc = new jsPDF('landscape');
function downloadDocs() {
var length = $(".classDivs").length / 2; // pdf splitting
for (let i = 0; i < length; i++) {
var chart = $('#div' + i)[0];
html2canvas(chart).then(function (canvas) {
doc.addImage(canvas.toDataURL('image/png'), 'JPEG', 10, 10, 180, 150);
if (i < (length - 1)) {
doc.addPage();
}
else if(i==length-1)
{
doc.save('pdfdocs.pdf');
}
});
}
}
The above is my main JavaScript code, if not this please suggest me other plugins paid versions as well, only thing is it must be client side.
Thanks in Advance.
By looking at the html2canvas code, the library happens to make use of the Promises feature which unfortunately is not being supported in any version of IE
http://caniuse.com/#search=promises
I made a test with the sample on the sites Below are working with Internet Explorer 11. So you can have a try and check whether it can solve your issue or not.
d3js/SVG Export demo
download svg
Other Reference:
DocRaptor
I have some webfonts that get loaded via Webfontloader load like this ...
<script src="//ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js"></script>
<script>
WebFont.load({
custom: {
families: ['BlenderProBook', 'BlenderProMedium']
}
});
</script>
And it works great when first loading the page ... Problems is, when refreshing the page it only retrieves the cached fonts when requested in html and not before my ReactJS app runs (when the Webfontloader normally gets them). This is too late for me, because I'm using them in pre-generated SVG.
Is there a way to force it to get the uncached fonts each time? Or better, load the cached fonts at the correct time.
I found a solution to this, which I will take as my answer if no-one else can supply a better one.
My font is being used extensively in the app to calculate text widths and therefore layout ... (which is why it needs to be loaded before the app runs), so I decided to use the text width code as a test to block the app from running.
Here's the code
var testFont = require('./components/svgText.js');
var timer = setInterval(function () {
var test = (testFont('TEST', 'BlenderProBook', 20).width === 39.75);
if (test) {
clearInterval(timer);
Router.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});
}
}, 50);
where svgTest.js uses Raphael SVG to generate SVG text and retrieve the measurements like this:-
renderedTextSize = function (string, font, fontSize) {
var paper = Raphael(0, 0, 0, 0);
paper.canvas.style.visibility = 'hidden';
var el = paper.text(0, 0, string);
el.attr('font-family', font);
el.attr('font-size', fontSize);
var bBox = el.getBBox();
paper.remove();
return {
width: bBox.width,
height: bBox.height
};
};
module.exports = renderedTextSize;
This seems to work quite nicely, even though it feels a bit hacky to be testing against a magic number (width).
I am using Highcharts in my application (without any internet connection)
I have multiple charts on a html page, and I want to generate a PDF report that contains all the charts from this page.
How can I do this without sending the data to any server on the internet ?
I will be thankful for any help or any example you can provide.
Thank you in advance :)
Yes this is possible but involves a few different libraries to get working. The first Library is jsPDF which allows the creation of PDF in the browser. The second is canvg which allows for the rendering and parsing of SVG's, the bit that is really cool though is it can render an svg on to canvas element. Lastly is Highcharts export module which will allow us to send the svg to the canvg to turn into a data URL which can then be given to jsPDF to turn into your pdf.
Here is an example http://fiddle.jshell.net/leighking2/dct9tfvn/ you can also see in there source files you will need to include in your project.
So to start highcharts provides an example of using canvg with it's export to save a chart as a png. because you want all the iamges in a pdf this has been slightly altered for our purpose to just return the data url
// create canvas function from highcharts example http://jsfiddle.net/highcharts/PDnmQ/
(function (H) {
H.Chart.prototype.createCanvas = function (divId) {
var svg = this.getSVG(),
width = parseInt(svg.match(/width="([0-9]+)"/)[1]),
height = parseInt(svg.match(/height="([0-9]+)"/)[1]),
canvas = document.createElement('canvas');
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
if (canvas.getContext && canvas.getContext('2d')) {
canvg(canvas, svg);
return canvas.toDataURL("image/jpeg");
}
else {
alert("Your browser doesn't support this feature, please use a modern browser");
return false;
}
}
}(Highcharts));
Then for the example i have set up export on a button click. This will look for all elements of a certain class (so choose one to add to all of your chart elements) and then call their highcharts.createCanvas function.
$('#export_all').click(function () {
var doc = new jsPDF();
// chart height defined here so each chart can be palced
// in a different position
var chartHeight = 80;
// All units are in the set measurement for the document
// This can be changed to "pt" (points), "mm" (Default), "cm", "in"
doc.setFontSize(40);
doc.text(35, 25, "My Exported Charts");
//loop through each chart
$('.myChart').each(function (index) {
var imageData = $(this).highcharts().createCanvas();
// add image to doc, if you have lots of charts,
// you will need to check if you have gone bigger
// than a page and do doc.addPage() before adding
// another image.
/**
* addImage(imagedata, type, x, y, width, height)
*/
doc.addImage(imageData, 'JPEG', 45, (index * chartHeight) + 40, 120, chartHeight);
});
//save with name
doc.save('demo.pdf');
});
important to note here that if you have lots of charts you will need to handle placing them on a new page. The documentation for jsPDF looks really outdated (they do have a good demos page though just not a lot to explain all the options possible), there is an addPage() function and then you can just play with widths and heights until you find something that works.
the last part is to just setup the graphs with an extra option to not display the export button on each graph that would normally display.
//charts
$('#chart1').highcharts({
navigation: {
buttonOptions: {
enabled: false
}
},
//this is just normal highcharts setup form here for two graphs see fiddle for full details
The result isn't too bad i'm impressed with the quality of the graphs as I wasn't expecting much from this, with some playing of the pdf positions and sizes could look really good.
Here is a screen shot showing the network requests made before and after the export, when the export is made no requests are made http://i.imgur.com/ppML6Gk.jpg
here is an example of what the pdf looks like http://i.imgur.com/6fQxLZf.png (looks better when view as actual pdf)
quick example to be tried on local https://github.com/leighquince/HighChartLocalExport
You need to setup your own exporting server, locally like in the article
Here is an example using the library pdfmake:
html:
<div id="chart_exchange" style="width: 450px; height: 400px; margin: 0 auto"></div>
<button id="export">export</button>
<canvas id="chart_exchange_canvas" width="450" height="400" style="display: none;"></canvas>
javascript:
function drawInlineSVG(svgElement, canvas_id, callback) {
var can = document.getElementById(canvas_id);
var ctx = can.getContext('2d');
var img = new Image();
img.setAttribute('src', 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgElement))));
img.onload = function() {
ctx.drawImage(img, 0, 0);
callback(can.toDataURL("image/png"));
}
}
full working code:
https://jsfiddle.net/dimitrisscript/f6sbdsps/
Maybe this link can help you out.
http://bit.ly/1IYJIyF
Try refer to the exporting properties (fallbackToExportServer: false) and the necessary file that need to be include (offline-exporting.js).
Whereas for the export all at once part, currently I myself also still trying. Will update here if any.
This question is a bit old but was something i was working on myself recently and had some trouble with it.
I used the jsPDF library: https://github.com/MrRio/jsPDF
Issues i ran into involved jsPDF not supporting the SVG image exported by the high chart + images being blurry and low quality.
Below is the solution I used to get two charts into one pdf document:
function createPDF() {
var doc = new jsPDF('p', 'pt', 'a4'); //Create pdf
if ($('#chart1').length > 0) {
var chartSVG = $('#chart1').highcharts().getSVG();
var chartImg = new Image();
chartImg.onload = function () {
var w = 762;
var h = 600;
var chartCanvas = document.createElement('canvas');
chartCanvas.width = w * 2;
chartCanvas.height = h * 2;
chartCanvas.style.width = w + 'px';
chartCanvas.style.height = h + 'px';
var context = chartCanvas.getContext('2d');
chartCanvas.webkitImageSmoothingEnabled = true;
chartCanvas.mozImageSmoothingEnabled = true;
chartCanvas.imageSmoothingEnabled = true;
chartCanvas.imageSmoothingQuality = "high";
context.scale(2, 2);
chartCanvas.getContext('2d').drawImage(chartImg, 0, 0, 762, 600);
var chartImgData = chartCanvas.toDataURL("image/png");
doc.addImage(chartImgData, 'png', 40, 260, 250, 275);
if ($('#chart2').length > 0) {
var chart2SVG = $('#chart2').highcharts().getSVG(),
chart2Img = new Image();
chart2Img.onload = function () {
var chart2Canvas = document.createElement('canvas');
chart2Canvas.width = w * 2;
chart2Canvas.height = h * 2;
chart2Canvas.style.width = w + 'px';
chart2Canvas.style.height = h + 'px';
var context = chart2Canvas.getContext('2d');
chart2Canvas.webkitImageSmoothingEnabled = true;
chart2Canvas.mozImageSmoothingEnabled = true;
chart2Canvas.imageSmoothingEnabled = true;
chart2Canvas.imageSmoothingQuality = "high";
context.scale(2, 2);
chart2Canvas.getContext('2d').drawImage(chart2Img, 0, 0, 762, 600);
var chart2ImgData = chart2Canvas.toDataURL("image/png");
doc.addImage(chart2ImgData, 'PNG', 300, 260, 250, 275);
doc.save('ChartReport.pdf');
}
chart2Img.src = "data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(chart2SVG)));
}
}
chartImg.src = "data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(chartSVG)));
}
}
scripts to include:
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
I have recently been learning about Firefox OS/B2G. I am aware of the extensive set of APIs in place that are able to fetch images from the wallpaper gallery, change settings and set reminders (to name a few). However, I'm completely stumped as to how to how to change the wallpaper, or, indeed, if this is even possible. Apologies if this is a silly question. Many thanks in advance.
You can do this by using a share activity
// imgToShare is the image you want to set as wallpaper
var shareImage = document.querySelector("#share-image"),
imgToShare = document.querySelector("#image-to-share");
if (shareImage && imgToShare) {
shareImage.onclick = function () {
if(imgToShare.naturalWidth > 0) {
// Create dummy canvas
var blobCanvas = document.createElement("canvas");
blobCanvas.width = imgToShare.width;
blobCanvas.height = imgToShare.height;
// Get context and draw image
var blobCanvasContext = blobCanvas.getContext("2d");
blobCanvasContext.drawImage(imgToShare, 0, 0);
// Export to blob and share through a Web Activitiy
blobCanvas.toBlob(function (blob) {
new MozActivity({
name: "share",
data: {
type: "image/*",
number: 1,
blobs: [blob]
}
});
});
}
else {
alert("Image failed to load, can't be shared");
}
};
}
You can test a live example with the Firefox OS boilerplate https://github.com/robnyman/Firefox-OS-Boilerplate-App/ .
How can I change a number in a time interval with Cocos2d Javascript engine?
With pure js I could use setInterval, but does any function in the cocos2d library do it?
You didn't write any code so I'll be using the one posted here.
To display a number in the center of the screen, that increases every second, I'd add this to MainLayer.js:
var MainLayer = cc.LayerColor.extend({
_labelNumber:null,
_number:0,
_updateRate:1.0,
onEnter:function () {
_number = 0;
var labelName = ""+_number;
_labelNumber = cc.LabelTTF.create(labelName, "Arial", 32);
_labelNumber.setColor(cc.c3(64, 64, 64));
_labelNumber.setPosition(winSize.width/2, winSize.height/2);
_updateRate = 1.0;
this.addChild(_labelNumber);
this.schedule(this.updateNumber, _updateRate);
},
updateNumber:function() {
_number++;
if(_labelNumber == null) return;
_labelNumber.setString(""+_number);
}
});