i am trying tp use a png as a mask in Cocos2d-JS
like so:
this.mask=cc.Sprite.create(cache.getSpriteFrame("bar_mask"));
this.maskedFill = cc.ClippingNode.create(this.mask);
this.maskedFill.setAlphaThreshold(0.5);
But it does not work ...
I found in other posts, that I have to enable the stencil buffer like
CCSetupDepthFormat: #GL_DEPTH24_STENCIL8_OES
But I have no idea how / where to do that in Cocos2d-JS
can anyone help?
Thanks!
It works for me without any additional depthFormat settings.
I'm using single-file engine cocos2d-js-v3.7.js
Here's the minimal code (hope it helps):
var game = cc.Layer.extend({
init:function () {
this._super();
backgroundLayer = cc.LayerColor.create(new cc.Color(40,40,40,255), 320, 480);
var target = cc.Sprite.create("resources/doge.png"); /*child to clip*/
var mask = cc.Sprite.create("resources/doge-mask.png"); /*mask*/
var maskedFill = new cc.ClippingNode(mask);
maskedFill.setAlphaThreshold(0.9);
maskedFill.addChild(target);
maskedFill.setPosition(144, 224);
backgroundLayer.addChild(maskedFill,0);
this.addChild(backgroundLayer);
}
});
Related
I have tried to implement a invert color function to my function, but I don't how to solve this thing with Cross Origin.
I have tried to use the "Anonymous", but that does not work too. So the question is pretty simple. How to use this getImageData correctly?
var canvasOriginal = document.getElementById("imagemOriginal");
var ctxOriginal = canvasOriginal.getContext("2d");
var imgOriginal = new Image();
var imgOut = new Image();
imgOriginal.src = 'images-png/img1.png';
imgOriginal.onload = function (){
ctxOriginal.drawImage(imgOriginal,0,0,512,512);
imgOut = ctxOriginal.getImageData(0,0,512,512);
for (let i = 0; i < imgOut.data.length; i += 4) {
imgOut.data[i] = 255 - imgOut.data[i];
imgOut.data[i+1] = 255 - imgOut.data[i+1];
imgOut.data[i+2] = 255- imgOut.data[i+2] ;
}
ctxOriginal.putImageData(imgOut, 512, 0);
};
Yes, I created a localhost and it has worked, but I had to add an extension on Google Chrome called "Allow-Control-Allow-Origin" to work. Thanks!
I think that the error is because your browser knows itself as localhost (or server you are on) and the canvas thinks your image is not coming from localhost or that server. If you're uploading locally your image should be something like
<img src="blob:http://your-server-address-or-localhost/image-id-returned-from-upload">
or if the image already exists, it would be something similar:
<img src="http://your-server-address-or-localhost/images-png/img1.png">
I imagine what you have is something like this:
<img src="/images-png/img1.png">
and that trips up the canvas
Your imgOriginal.src should be:
imgOriginal.src = 'http://localhost:3000/images-png/img1.png';
Hope this helps.
I'm trying a basic display of a preloaded image with p5.js library (instantiation mode):
var sketch = function(p) {
var fondo;
p.preload = function() {
fondo = p.loadImage('app/themes/mrg/dist/images/tramas/example.jpg');
};
var viewportWidth = $(window).width();
p.setup = function(){
canvas = p.createCanvas(viewportWidth, 200);
canvas.background(255);
canvas.image(fondo, 0, 0);
};
};
new p5(sketch);
The canvas was created but no image is there.
Here is a working example:
https://stage.margenesdelarte.org/
The canvas is at the end of the page (with white background) but no image is rendered inside.
Image path is right, since there is no error in the console and it can be reached in its place:
https://stage.margenesdelarte.org/app/themes/mrg/dist/images/tramas/example.jpg
What is wrong, and how can I display this image? Thanks!
That's correct version? (I used BASE64 because I didn't want to run a local server)
var sketch = function(p) {
var fondo;
p.preload = function() {
fondo = p.loadImage("data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAwAAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFzByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSpa/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJlZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uisF81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PHhhx4dbgYKAAA7");
};
var viewportWidth = 500;
p.setup = function(){
var canvas = p.createCanvas(viewportWidth, 200);
canvas.image(fondo, 0, 0); // doesn't work
p.image(fondo, 0, 0); // works fine
console.log(p.image, canvas.image); //there are different functions
};
};
new p5(sketch);
https://codepen.io/anon/pen/yPENXx?editors=1111
Explanation:
Both p and canvas has a image function but there are different image functions. You have to use p.image(). I think canvas.image() is has some relations with https://p5js.org/reference/#/p5.Image, but that's only my assumptions.
Is your file being localhosted? For p5 to access local files such as images, it needs to be localhosted... I recommend apache
Has anyone taken the time to extract the timeline widget from the Cesium app? I'm looking to use the timeline widget without the Dojo dependency. I was able to find a teaser saying that it's possible, but the timeline example isn't the easiest to reverse engineer. Does anyone have an idea of how I can extract the necessary libraries and remove the Dojo dependency?
google groups timeline discussion
cesium timeline demo
The timeline itself (outside of that demo app) does not use Dojo. Here's a sample of how this works. You can Run this demo on Sandcastle.
function onTimelineScrubfunction(e) {
var clock = e.clock;
clock.currentTime = e.timeJulian;
clock.shouldAnimate = false;
}
var timeControlsContainer = document.getElementById('timeControlsContainer');
var clock = new Cesium.Clock();
var clockViewModel = new Cesium.ClockViewModel(clock);
var animationContainer = document.createElement('div');
animationContainer.className = 'cesium-viewer-animationContainer';
timeControlsContainer.appendChild(animationContainer);
var animation = new Cesium.Animation(animationContainer, new Cesium.AnimationViewModel(clockViewModel));
var timelineContainer = document.createElement('div');
timelineContainer.className = 'cesium-viewer-timelineContainer';
timeControlsContainer.appendChild(timelineContainer);
var timeline = new Cesium.Timeline(timelineContainer, clock);
timeline.addEventListener('settime', onTimelineScrubfunction, false);
timeline.zoomTo(clock.startTime, clock.stopTime);
clockViewModel.shouldAnimate = true;
window.setInterval(function() {
clock.tick();
}, 32);
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 am new to Cocos2d-html5 v2.2.1 and I am trying to add a sprite (simple image) to the canvas. The code does add an image with the correct width and height but it is just black.
I cant seem to find any errors so I am kinda stuck.
Any help would be great. My code is below:
In main.js i load the resources:
applicationDidFinishLaunching:function () {
if(cc.RenderDoesnotSupport()){
//show Information to user
alert("Browser doesn't support WebGL");
return false;
}
// initialize director
var director = cc.Director.getInstance();
//cc.EGLView.getInstance()._adjustSizeToBrowser();
//cc.EGLView.getInstance()._resizeWithBrowserSize(true);
//cc.EGLView.getInstance().setDesignResolutionSize(600, 400, cc.RESOLUTION_POLICY.SHOW_ALL);
// set FPS. the default value is 1.0/60 if you don't call this
director.setAnimationInterval(1.0 / this.config['frameRate']);
//load resources
cc.LoaderScene.preload(g_resources, function () {
director.replaceScene(new this.startScene());
}, this);
return true;
}
g_resources is defined in resource.js:
var s_jet = "images/jet.png";
var s_character = "images/p1_front.png";
var g_resources = [
//image
{src:s_jet},
{src:s_character}];
spriteScene.js:
init:function () {
var selfPointer = this;
this._super();
var size = cc.Director.getInstance().getWinSize();
var lazyLayer = cc.LayerColor.create(new cc.Color4B(45, 50, 128, 255), 600, 600);
//var lazyLayer = cc.Layer.create();
lazyLayer.setAnchorPoint(new cc.Point(0.5,0.5));
var characterSprite = cc.Sprite.create("./images/p1_front.png");
lazyLayer.addChild(characterSprite, 0);
this.addChild(lazyLayer);
var rotateToA = cc.RotateTo.create(2, 0);
var scaleToA = cc.ScaleTo.create(2, 1, 1);
characterSprite.setPosition(new cc.Point(size.width/2,size.height/2));
I just dont understand why the sprite is just being drawn as a black box.
Edit: When I uncomment the line below from main.js; at first the image is still black but when I resize the browser, the image appears:-
cc.EGLView.getInstance().setDesignResolutionSize(600, 400, cc.RESOLUTION_POLICY.SHOW_ALL);
I dont know what this is implying.
Ok guys! I figured it out and I am pissed. Changed this line:
this.characterSprite.setPosition(new cc.Point(size.width/2,size.height/2));
to:
this.characterSprite.setPosition(cc.p(size.width/2, size.height/2));
Documentation/tutorials for cocos2d-html5 are outdated and this is getting frustrating.