gjs cairo context drawing not displaying in clutter window - javascript

I'm trying to get a simple cairo drawing drawn to a clutter window using the javascript bindings. My problem is, apart from half the functions being named slightly differently, is no matter what I try, the cairo drawing does not show up. I used a example from python, which does work, and ported it to javascript. I'm also using introspection to get the Clutter module instance. I'm also using gjs version 0.7.14. Can anyone tell me what is going wrong.
Below is the example code I'm using.
const cairo = imports.cairo;
const clutter = imports.gi.Clutter;
function on_button_press_event (stage, event) {
clutter.main_quit();
}
function draw(cairo_tex) {
var context = cairo_tex.create();
context.scale(200, 200);
context.setLineWidth(0.1);
var colour2 = new clutter.Color();
colour2.from_string('#dd000088');
clutter.cairo_set_source_color(context, colour2);
context.translate(0.5, 0.5);
context.arc(0, 0, 0.4, 0, Math.PI * 2);
context.stroke();
}
function main () {
clutter.init(0, null);
var stage = new clutter.Stage();
var colour = new clutter.Color();
colour.from_string("#ffccccff");
stage.set_color(colour);
stage.set_size(400, 300);
stage.connect('button-press-event', on_button_press_event);
stage.connect('destroy', clutter.main_quit);
var cairo_tex = new clutter.CairoTexture.new(200, 200);
cairo_tex.set_position((stage.get_width() - 200) / 2,
(stage.get_height() - 200) / 2);
draw(cairo_tex);
var center_x = cairo_tex.get_width() / 2;
var center_z = cairo_tex.get_height() / 2;
cairo_tex.set_rotation(clutter.AlignAxis.Y_AXIS, 45.0, center_x, 0, center_z);
stage.add_actor(cairo_tex);
cairo_tex.show();
stage.show();
clutter.main();
}
main();
I think the reason this is not working has to do with the deletion of the cairo context in javascript. context.destroy does not exist and using delete doesn't either. Infact if I use delete then I get the warning
WARNING: 'applying the 'delete' operator to an unqualified name is deprecated'
which does not help at all. According to what some of the developers involved in gjs have posted about it, assigning to null should have the same effect, due to it being garbage collected. I'm having my doubts as to whether there is anything to collect behind the scenes.
If someone could say if this is true or not, then I would accept this as a answer.
UPDATE:
I have narrowed down the problem area to imports.gi.Clutter. I tried another example, but this time using Gtk instead of Clutter, and the following code actually works
cairo = imports.cairo;
Gtk = imports.gi.Gtk;
Gdk = imports.gi.Gdk;
function draw_arc(drawing_area){
var cr = Gdk.cairo_create(drawing_area.get_window());
cr.scale(2, 2);
cr.operator = cairo.Operator.CLEAR;
cr.paint();
cr.operator = cairo.Operator.OVER;
cr.setSourceRGB(0,255,0);
cr.arc(128, 128, 76.8, 0, 2*Math.PI);
cr.fill();
return false;
}
Gtk.init(0, null);
var w = new Gtk.Window();
w.connect('delete-event', Gtk.main_quit);
var d = new Gtk.DrawingArea();
w.add(d);
w.resize(500,600);
w.decorated = false;
d.connect('draw', draw_arc);
w.show_all();
Gtk.main();
This leads me to believe that the problem is not with the gjs implementation of cairo, but with the gjs introspection methods for Clutter Cairo implementation. I'm thinking that clutter.CairoTexture.new or clutter.CairoTexture.create is not implemented properly. I suspect it is the clutter.CairoTexture.create which is causing the problem.

Using the newer integration between Clutter, and Cairo, specifically the Clutter.Canvas this will draw a circle to the screen:
const Clutter = imports.gi.Clutter;
const Cairo = imports.cairo;
const draw_stuff = function (canvas, cr, width, height) {
cr.save ();
cr.setOperator (Cairo.Operator.CLEAR);
cr.paint ();
cr.restore ();
cr.setOperator (Cairo.Operator.OVER);
cr.scale (width, height);
cr.setLineCap (Cairo.LineCap.ROUND);
cr.setLineWidth (0.1);
cr.translate (0.5, 0.5);
cr.arc (0, 0, 0.4, 0, Math.PI * 2);
cr.stroke ();
return true;
};
const test = function () {
Clutter.init(null);
let stage = new Clutter.Stage();
stage.set_title ("Circle!");
let color = new Clutter.Color({
red : 255,
green : 0,
blue : 0,
alpha : 128 // Just for the heck of it.
});
stage.set_background_color(color);
stage.set_size(300, 300);
let canvas = new Clutter.Canvas ();
canvas.set_size (155, 155);
let dummy = new Clutter.Actor ();
dummy.set_content (canvas);
dummy.set_size(155, 155);
stage.add_child (dummy);
stage.connect ("destroy", Clutter.main_quit);
canvas.connect ("draw", draw_stuff);
canvas.invalidate ();
stage.show_all();
Clutter.main ();
};
test ();

Related

Cannot add bitmapdata to group - phaser

I'm asking this question continuing from How can I fix bitmapdata to the camera in Phaser? I tried it and it worked, however I found that the bitmapdata wouldn't update. My current code:
bitmap = game.add.bitmapData(800, 100);
bitmapSprite = game.add.sprite(0, 0, bitmap);
bitmapSprite.fixedToCamera = true;
I've tried:
bitmap = game.add.bitmapData(800, 100);
bitmapSprite = game.add.sprite(0, 0);
bitmapSprite.addChild(bitmap);
bitmapSprite.fixedToCamera = true;
And:
bitmap = Game.add.bitmapData(800, 100);
bitmap.dirty = true;
bitmapSprite = Game.add.sprite(0, 0);
bitmapSprite.fixedToCamera = true;
var group = Game.add.group();
group.add(bitmap);
group.add(bitmapSprite);
This is the error I get for the first:
Uncaught TypeError: this.children[t].updateTransform is not a function
This is the second error:
Uncaught TypeError: e.preUpdate is not a function
I am using Phaser CE v2.8.7.
EDIT:
Found a solution:
Whenever I want to update the bitmapdata I simply use this:
bitmapSprite.loadTexture(bitmapSprite)
You have to make sure the dirty property is set to true:
bitmap.dirty = true
Thanks.

Errors with greensock tween activated by mouse in pixi.js

I'm trying to scroll a greensock tween in pixi. I'm getting errors trying to hook the code that gets the mouse/arrow input (trackpad.value) with my tween.
Here's my working greensock test tween, to make sure I have greensock working in pixi: (have to tween the position element in pixi):
var t1 = new TimelineMax({onUpdate:animate, onUpdateScope:stage});
t1.to(bg.position, 3, {y:100});
Here's my code where I'm trying to hook trackpad.value into the greensock code (I'm getting the following error: Uncaught TypeError: bg.position is not a function):
trackpad = new Trackpad(document);
var t1 = new TimelineMax({paused:true, onUpdate:animate, onUpdateScope:stage});
t1.progress(bg.position( Math.abs( trackpad.value ) / 3240));
I then tried the following - it didn't work (but I didn't get an error):
var moveIt = trackpad.value / 3240;
t1.progress(bg.position, moveIt, {});
Here's the code where the trackpad value is defined:
/*
* param: the html element that will be scrolled
*/
Trackpad = function(target)
{
this.target = target;
this.value = 0;
this.easingValue = 00;
this.dragOffset = 0;
this.dragging;
this.speed= 0;
this.prevPosition = 0;
$(this.target).mousedown($.proxy(this.onMouseDown, this));
this.target.onmousewheel = $.proxy(this.onMouseWheel, this);
// not forgetting touchs!
this.target.ontouchstart = $.proxy(this.onTouchStart, this);
// stop dragging!
$(document).keydown( $.proxy(this.onArrow, this))//function(e){
//this.target.ondragstart = function(){return false;}
}
// set constructor
Trackpad.constructor = Trackpad;
// create the functions
Trackpad.prototype.unlock = function()
{
this.locked = false;
this.speed = 0;
this.easingValue = this.value;
}
Trackpad.prototype.lock = function()
{
this.locked = true;
}
Trackpad.prototype.update = function()
{
if(this.easingValue > 0)this.easingValue = 0;
if(this.easingValue < -10700)this.easingValue = -10700;
this.value = this.easingValue;
if(this.dragging)
{
var newSpeed = this.easingValue - this.prevPosition;
newSpeed *= 0.7;
this.speed += (newSpeed - this.speed) *0.5;//+= (newSpeed - this.speed) * 0.5;
this.prevPosition = this.easingValue;
}
else
{
this.speed *= 0.9;
this.easingValue += this.speed;
if(Math.abs(this.speed) < 1)this.speed = 0;
}
}
Trackpad.prototype.onArrow = function(event)
{
if (event.keyCode == 38) {
// UP
this.speed = 4;
return false;
}
else if (event.keyCode == 40) {
// UP
this.speed -= 4
return false;
}
}
Trackpad.prototype.onMouseWheel = function(event)
{
event.preventDefault();
this.speed = event.wheelDelta * 0.1;
}
Trackpad.prototype.startDrag = function(newPosition)
{
if(this.locked)return;
this.dragging = true;
this.dragOffset = newPosition - this.value;
}
Trackpad.prototype.endDrag = function(newPosition)
{
if(this.locked)return;
this.dragging = false;
}
Trackpad.prototype.updateDrag = function(newPosition)
{
if(this.locked)return;
this.easingValue = (newPosition - this.dragOffset);
}
/*
* MOUSE
*/
Trackpad.prototype.onMouseDown = function(event)
{
if(event)event.preventDefault();
event.returnValue = false;
$(document).mousemove($.proxy(this.onMouseMove, this));
$(document).mouseup($.proxy(this.onMouseUp, this));
this.startDrag(event.pageY);
}
Trackpad.prototype.onMouseMove = function(event)
{
if(event)event.preventDefault();
this.updateDrag(event.pageY);
}
Trackpad.prototype.onMouseUp = function(event)
{
//$(this.target).mousemove(null);
$(document).unbind('mousemove');
$(document).unbind('mouseup');
//this.target.onmousemove = null;
this.endDrag();// = false;
}
/*
* TOUCH!
*/
Trackpad.prototype.onTouchStart = function(event)
{
//event.preventDefault();
this.target.ontouchmove = $.proxy(this.onTouchMove, this);
this.target.ontouchend = $.proxy(this.onTouchEnd, this);
this.startDrag(event.touches[0].clientY);
}
Trackpad.prototype.onTouchMove = function(event)
{
event.preventDefault();
this.updateDrag(event.touches[0].clientY);
}
Trackpad.prototype.onTouchEnd = function(event)
{
this.target.ontouchmove = null;
this.target.ontouchend = null;
this.endDrag();
}
** edit
tl = new TimelineLite( { paused: true } );
// respond to scroll event - in this case using jquery
$(window).scroll();
//apply whatever math makes the most sense to progress the timeline progress from 0 to 1 within those parameters. Something like,
$(window).scroll( function() {
var st = $(this).scrollTop();
if ( st < someArbitraryValue ) { // someArbitraryValue, where to start
// Here, "someOtherArbitaryValue" would be the
// "height" of the scroll to react to
tl.progress( Math.abs( st ) / someOtherArbitaryValue );
}
});
Is this the kind of effect you were after?
JavaScript:
window.requestAnimFrame=(function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(callback){window.setTimeout(callback,1000/60);};})(); //http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
var stageWidth=$(window).innerWidth();
var stageHeight=$(window).innerHeight();
var renderer=PIXI.autoDetectRenderer(stageWidth,stageHeight);
var bg,cat,moon,blue,trackpad,texture1,texture2,texture3;
document.body.appendChild(renderer.view);
texture1=PIXI.Texture.fromImage('https://dl.dropboxusercontent.com/u/45891870/Experiments/StackOverflow/1.5/cat.jpg');
texture2=PIXI.Texture.fromImage('https://dl.dropboxusercontent.com/u/45891870/Experiments/StackOverflow/1.5/moon.jpg');
texture3=PIXI.Texture.fromImage('https://dl.dropboxusercontent.com/u/45891870/Experiments/StackOverflow/1.5/blue.jpg');
bg=new PIXI.Container();
cat=new PIXI.Sprite(texture1);
moon=new PIXI.Sprite(texture2);
blue=new PIXI.Sprite(texture3);
cat.anchor.x=cat.anchor.y=moon.anchor.x=moon.anchor.y=blue.anchor.x=blue.anchor.y=0;
cat.position.x=cat.position.y=moon.position.x=blue.position.x=bg.position.x=bg.position.y=0;
cat.width=moon.width=blue.width=stageWidth;
moon.position.y=1080;
blue.position.y=2160;
bg.addChild(cat);
bg.addChild(blue);
bg.addChild(moon);
bg.vy=bg.vx=0;//what are those?
trackpad=new Trackpad(document);
requestAnimFrame(animate);
function animate(){
requestAnimFrame(animate);
bg.position.y=trackpad.value;
trackpad.update();
renderer.render(bg);
}
Let me know if this is exactly the thing you were looking for & I'll then break it down for you in terms of what has changed in comparison to your code.
Notes:
First & foremost, I have used the latest version (v3.0.6) of Pixi.JS in my example above. This v3 update brought a few major changes. Couple of them prominent to your problem are:
No need for Stage object anymore for rendering purposes. Any Container type object can be used directly to be rendered on canvas.
Shortening of the name DisplayObjectContainer to simply Container. This is probably the reason why you are getting the error when trying to implement my code in your environment that you mentioned in comments because I presume you are using one of the old verions.
Read all about this update here, here & here.
I always prefer to use the latest & greatest of GSAP (v1.17.0‏). Even the dot releases of this framework brings major updates which is why I like to keep it up to date. Read an important note on this update here. Having said that, the current implementation doesn't really use TweenMax at all.
TweenMax bundles EasePack, CSSPlugin & a few other things. No need to load them in separately. Update your HTML accordingly. Use this handy GSAP CheatSheet by Peter Tichy to get such information and more about this tool.
Changes in Trackpad.js:
Inside the update method, there was a maximum scroll limit defined the page can scroll up to. That value previously was -10700. I changed it to -2160. You may want to set it to -3240 I think, based on what I have been able to understand so far as to what you are trying to achieve.
Formatting changes.
Changes in main.js (whatever name you gave to your main script file):
Added a requestAnimationFrame polyfill thanks to Paul Irish.
Removed the var stage= new PIXI.Stage(0xff00ff); line. Read #1 above for details.
Renamed DisplayObjectContainer to Container which was assigned to bg. Read #1 above for details.
Added bg.position.y=trackpad.value; in the animate loop. You were missing this. You will need to use trackpad.value in order to position your bg.
Added trackpad.update(); in the same animate loop. This is the big one and IMHO, this is the one you were failing to understand the purpose of. In summary, Trackpad.js needs to update its value on a timely basis & the only loop you have got running is the animate loop thanks to requestAnimFrame. Hence, the update(); method is called.
Rendering bg instead of stage. Read #1 above for details.
Formatting changes.
Let me know if anything is unclear.
T
I thought of editing the old answer but decided against it because I think it answers your original question.
Take a look at this Codepen demo for a new approach to the same problem. I am really hoping to listen to community on the approach I have taken here in terms of listening to events and using them to adjust a GSAP timeline.
There are 4 JS files used in my example: app.js, constants.js, timeline.js & listeners.js. Links to which can be found in the settings gear icon of the JavaScript editor of the demo. All of these files are heavily annotated with links to solutions I found over the internet to specific problems.
Among these files, code of app.js is as follows:
JavaScript:
function Application(){}
Application.prototype.init=function(){
this.constants=Constants.getInstance();
this.BASE_URL=this.constants.BASE_URL;
this.IMAGE_JS_URL=this.constants.IMAGE_JS_URL;
this.IMAGE_PIXI_URL=this.constants.IMAGE_PIXI_URL;
this.IMAGE_GSAP_URL=this.constants.IMAGE_GSAP_URL;
this.createPolyfillForBind();
this.setupRenderer();
this.loadImages();
};
Application.prototype.setupRenderer=function(){
this.stageWidth=window.innerWidth;
this.stageHeight=window.innerHeight;
//this.renderer=PIXI.autoDetectRenderer(this.stageWidth,this.stageHeight);
this.renderer=new PIXI.CanvasRenderer(this.stageWidth,this.stageHeight);
document.body.appendChild(this.renderer.view);
};
Application.prototype.loadImages=function(){
var self=this;
this.loader=new PIXI.loaders.Loader(this.BASE_URL,1,{crossOrigin:''}); // PIXI Loader class [http://pixijs.github.io/docs/PIXI.loaders.Loader.html]
this.loader.add(this.IMAGE_JS_URL); // Loader extends ResourceLoader [http://adireddy.github.io/docs/haxe-pixi/v3/types/pixi/plugins/resourceloader/ResourceLoader.html]
this.loader.add(this.IMAGE_PIXI_URL);
this.loader.add(this.IMAGE_GSAP_URL);
//this.loader.once('complete',function(){self.onImagesLoaded.apply(self);}); // Vanilla JS alternative to jQuery's proxy() method [http://stackoverflow.com/a/4986536]
this.loader.once('complete',this.onImagesLoaded.bind(this)); // bind() polyfill [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Polyfill]
this.loader.load();
};
Application.prototype.onImagesLoaded=function(){
this.setupSprites();
this.initTimeline();
this.initListeners();
this.startTicker();
};
Application.prototype.setupSprites=function(){
this.containerBg=new PIXI.Container();
this.spriteJS=new PIXI.Sprite(PIXI.utils.TextureCache[this.BASE_URL+this.IMAGE_JS_URL]); // TextureCache in action [http://www.html5gamedevs.com/topic/7674-load-textures-synchronously/?p=45836]
this.spritePIXI=new PIXI.Sprite(PIXI.utils.TextureCache[this.BASE_URL+this.IMAGE_PIXI_URL]); // PIXI.TextureCache became PIXI.utils.TextureCache in v3 [http://www.html5gamedevs.com/topic/14144-v3-utilstexturecache-utils-is-not-defined/?p=80524]
this.spriteGSAP=new PIXI.Sprite(PIXI.utils.TextureCache[this.BASE_URL+this.IMAGE_GSAP_URL]);
this.containerBg.addChild(this.spriteJS);
this.containerBg.addChild(this.spritePIXI);
this.containerBg.addChild(this.spriteGSAP);
this.spriteJS.anchor.x=this.spriteJS.anchor.y=this.spritePIXI.anchor.x=this.spritePIXI.anchor.y=this.spriteGSAP.anchor.x=this.spriteGSAP.anchor.y=0;
this.spriteJS.position.x=this.spriteJS.position.y=this.spritePIXI.position.x=this.spriteGSAP.position.x=this.containerBg.position.x=this.containerBg.position.y=0;
this.scaleImage(this.spriteJS);
this.scaleImage(this.spritePIXI);
this.scaleImage(this.spriteGSAP);
this.spritePIXI.alpha=this.spriteGSAP.alpha=0;
this.spriteJS.position.y=this.constants.GUTTER;
this.spritePIXI.position.y=this.spriteJS.height*2+this.constants.GUTTER;
this.spriteGSAP.position.y=this.spriteJS.height+this.spritePIXI.height*2+this.constants.GUTTER;
};
Application.prototype.scaleImage=function(sprite){
//var scale=Math.min(this.stageWidth/sprite.width,this.stageHeight/sprite.height); // resize with aspect ratio [http://community.createjs.com/discussions/createjs/547-resizing-canvas-and-its-content-proportionally-cross-platform#comment_27266530] and [https://opensourcehacker.com/2011/12/01/calculate-aspect-ratio-conserving-resize-for-images-in-javascript/]
var scale=this.stageWidth/sprite.width;
sprite.scale.x=sprite.scale.y=scale;
};
Application.prototype.initTimeline=function(){
this.timeline=new Timeline();
this.timeline.init(this.containerBg,this.spriteJS,this.spritePIXI,this.spriteGSAP,this.stageWidth,this.stageHeight);
};
Application.prototype.initListeners=function(){
var self=this;
//this.listeners=new Listeners();
//this.constants.setListenersObject(this.listeners);
//this.listeners.init();
this.listeners=Listeners.getInstance();
this.listeners.addListeners();
document.addEventListener(this.constants.SCROLLED,this.onScroll.bind(this),false);
document.addEventListener(this.constants.STARTED_DRAG,this.onStartDrag.bind(this),false);
document.addEventListener(this.constants.DRAGGED,this.onDrag.bind(this),false);
document.addEventListener(this.constants.END_DRAG,this.onEndDrag.bind(this),false);
};
Application.prototype.onScroll=function(e){ this.timeline.onScroll(e); };
Application.prototype.onStartDrag=function(e){ this.timeline.onStartDrag(e); };
Application.prototype.onDrag=function(e){ this.timeline.onDrag(e); };
Application.prototype.onEndDrag=function(e){ this.timeline.onEndDrag(e); };
Application.prototype.startTicker=function(){
var self=this;
//TweenLite.ticker.addEventListener('tick',function(){self.render.apply(self);},false); // Vanilla JS alternative to jQuery's proxy() method [http://stackoverflow.com/a/4986536]
TweenLite.ticker.addEventListener('tick',this.render.bind(this),false);
};
Application.prototype.render=function(){this.renderer.render(this.containerBg);};
Application.prototype.createPolyfillForBind=function(){ // [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Polyfill]
if(!Function.prototype.bind){
Function.prototype.bind=function(oThis){
if(typeof this!=='function'){
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs=Array.prototype.slice.call(arguments,1),
fToBind=this,
fNOP=function(){},
fBound=function(){
return fToBind.apply(this instanceof fNOP
?this
:oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype=this.prototype;
fBound.prototype=new fNOP();
return fBound;
};
}
};
//
var app=new Application();
app.init();
P.S. I have also heavily experimented with design patterns in this same example, mainly Prototype and Singleton patterns. I am also looking forward to comments on them as well from the community.
T

How to get the current pattern-object contents of a canvas-context (2D)?

(Using Firefox32, and Win7. But in other browsers I need it to work, too.)
I can't find a command to retrieve the content of the pattern-object that I set on the 2D-context.
Is there no direct way to get the value array and the width and height?
And if there is really no direct way, is there a workaround?
I could just use fillRect with the pattern on a hidden canvas and then reading out the canvas. But then, how to get the correct height and width?
Pattern properties
The only method exposed on the CanvasPattern object is to handle transformations:
interface CanvasPattern {
// opaque object
void setTransform(SVGMatrix transform);
};
This means all other properties has to be tracked externally.
Workaround 1 - manually keep track of properties
The workaround is to read the width and height from the image you used for the pattern, as well as mode and optionally transforms.
Just keep a reference to them for later:
var img = ...; // image source
var patternMode = "repeat"; // store repeat mode
var patternWidth = img.naturalWidth; // width and height of image
var patternHeight = img.naturalHeight; // = width and height of pattern
var pattern = ctx.createPattern(img, patternMode); // use to create pattern
Workaround 2 - create a custom object
You can create a custom object which wraps up the pattern creation process and exposes methods that can hold width, height etc.
Example
An object could look like this:
function PatternExt(ctx, image, mode) {
var ptn = ctx.createPattern(image, mode || "repeat");
this.setTransform = ptn.setTransform ? ptn.setTransform.bind(ptn) : null;
this.width = image.naturalWidth;
this.height = image.naturalHeight;
this.image = image;
this.mode = mode;
this.pattern = ptn;
}
Then it's just a matter of creating an instance almost the same way as with createPattern():
var p = new PatternExt(ctx, img, "repeat");
ctx.fillStyle = p.pattern;
To read information do:
var w = p.width;
var h = p.height;
...
Rename/extend as you want/need.
Demo for custom object
// load an image for pattern
var img = new Image();
img.onload = demo;
img.src = "http://i.imgur.com/HF5eJZS.gif";
function demo() {
var ctx = document.querySelector("canvas").getContext("2d"), p;
// create a pattern instance
p = new PatternExt(ctx, img, "repeat");
// use as fill-style
ctx.fillStyle = p.pattern;
ctx.fillRect(0, 0, 300, 150);
// show some properties
ctx.font = "24px sans-serif";
ctx.fillStyle = "#fff";
ctx.fillText([p.width, p.height, p.mode].join(), 10, 30);
}
function PatternExt(ctx, image, mode) {
var ptn = ctx.createPattern(image, mode || "repeat");
this.setTransform = ptn.setTransform ? ptn.setTransform.bind(ptn) : null;
this.width = image.naturalWidth;
this.height = image.naturalHeight;
this.image = image;
this.mode = mode;
this.pattern = ptn;
}
<canvas></canvas>
If your desired pattern is currently used as the fillStyle, then you can fetch it by fetching the fillStyle:
myPattern=context.fillStyle;
Otherwise you can't fetch your pattern object because the context keeps any pattern objects you've created as private properties.
So typically you keep a reference to your pattern until it's not needed anymore.
If you also need the original imageObject used to create your pattern then you typically save a reference to that image also.
// create an imageObject for use in your pattern
var myImageObject=new Image();
myImageObject.onload=start; // call start() when myImageObject is fully loaded
myImageObject.src="";
function start(){
// myImageObject has now been fully loaded so
// create your pattern and keep a reference to it
var myPattern = context.createPattern(myImageObject, 'repeat');
}
... and later when you need the pattern ...
// use your pattern object reference to apply the pattern as a fillStyle
context.fillStyle = myPattern;
... and later if you need the original image object
// get the original image object's size
var imgWidth=myImageObject.width;
var imgHeight=myImageObject.height;
// draw the original image object to the context -- or whatever you need it for
context.drawImage(myImageObject,50,50);

EaselJS: BitmapSequence issue in a OOP-like class

I have been playing a bit with gskinner.com's EaselJS library (http://easeljs.com/, http://easeljs.com/examples/game/game.html), which makes dealing with HTML5's canvas a lot easier.
So I'm trying to remake something like Space Invaders in the canvas. So far it's not much, just the payer moving left to right. See the progress here: http://jansensan.net/experiments/easeljs-space-invader/
For the invaders, I needed an animation, so I followed a tutorial on how to do so: http://www.youtube.com/watch?v=HaJ615V6qLk
Now that is all good and dandy, however I follow gskinner.com's way of creating "classes": http://easeljs.com/examples/game/Ship.js I'm not certain if I can call that a class, but it is used as such.
So below is the class that I wrote for the Invader, however it seems like the BitmapSequence does not seem to be added to EaselJS's stage. Anyone can guide me through this? Thanks!
// REFERENCES
/*
http://easeljs.com/examples/game/Ship.js
*/
// CLASS
(function(window)
{
function Invader()
{
this.initialize();
}
var p = Invader.prototype = new Container();
// CONSTANTS
// VARS
p.image;
p.bitmapSequence;
// CONSTRUCTOR
p.Container_initialize = p.initialize; //unique to avoid overiding base class
p.initialize = function()
{
this.Container_initialize();
this.image = new Image();
this.image.onload = p.imageLoadHandler;
this.image.onerror = p.imageErrorHandler;
this.image.src = "assets/images/invader-spritesheet.png";
}
p.imageLoadHandler = function()
{
var frameData = {
anim:[0, 1, "anim"]
}
var spriteSheet = new SpriteSheet(p.image, 22, 16, frameData);
p.bitmapSequence = new BitmapSequence(spriteSheet);
p.bitmapSequence.regX = p.bitmapSequence.spriteSheet.frameWidth * 0.5;
p.bitmapSequence.regY = p.bitmapSequence.spriteSheet.frameHeight * 0.5;
p.bitmapSequence.gotoAndStop("anim");
p.addChild(p.bitmapSequence);
}
p.imageErrorHandler = function()
{
console.log("Error: the url assets/images/invader-spritesheet.png could not be loaded.");
}
window.Invader = Invader;
}(window));
Does you p.image/this.Container_initalize actually exist at that point? As you switch between using this. and p. between your init and other functions, while they might seem to be the same practice has often taught me its not the case. Try changing your init function to this:
p.initialize = function()
{
p.Container_initialize();
p.image = new Image();
p.image.onload = p.imageLoadHandler;
p.image.onerror = p.imageErrorHandler;
p.image.src = "assets/images/invader-spritesheet.png";
}

Creating a simple drawing area widget with google closure

Here I've tried to create a simple drawing area widget containing a single circle, using google closure.
I load it by calling sketcher.load() within html script tag and get an error:
Uncaught TypeError: Cannot set property 'Widget' of undefined - what is not right here?
goog.provide('sketcher');
goog.require('goog.dom');
goog.require('goog.graphics');
goog.require('goog.ui.Component');
var sketcher = {};
sketcher.prototype.Widget = function(el){
goog.ui.Component.call(this);
this.parent_ = goog.dom.getElement(el);
this.g_ = new goog.graphics.createGraphics(600, 400);
this.appendChild(this.g_);$
var fill = new goog.graphics.SolidFill('yellow');
var stroke = new goog.graphics.Stroke(1,'black');
circle = this.g_.drawCircle(300, 200, 50, stroke, fill);
this.g_.render(this._parent);
};
goog.inherits(sketcher.Widget, goog.ui.Component);
sketcher.prototype.load = function(){
var canvas = goog.dom.createDom('div', {'id':'canvas'});
goog.dom.appendChild(document.body, canvas);
var widget = new sketcher.Widget(canvas);
};
First problem: sketcher is a namespace, because you goog.provide it. You don't need to declare it again.
Second problem: sketcher.Widget should be thus, not sketcher.prototype.Widget. Only functions have prototypes; you should go back and review how objects work in JavaScript unless that was just a typo. It should look like this.
goog.provide('sketcher');
goog.require('goog.dom');
goog.require('goog.graphics');
goog.require('goog.ui.Component');
/**
* My sketcher widget.
* #param {Element} e1
* #constructor
*/
sketcher.Widget = function(el){
goog.ui.Component.call(this);
this.parent_ = goog.dom.getElement(el);
this.g_ = new goog.graphics.createGraphics(600, 400);
this.appendChild(this.g_);$
var fill = new goog.graphics.SolidFill('yellow');
var stroke = new goog.graphics.Stroke(1,'black');
circle = this.g_.drawCircle(300, 200, 50, stroke, fill);
this.g_.render(this._parent);
};
goog.inherits(sketcher.Widget, goog.ui.Component);
sketcher.prototype.load = function(){
var canvas = goog.dom.createDom('div', {'id':'canvas'});
goog.dom.appendChild(document.body, canvas);
var widget = new sketcher.Widget(canvas);
};
here is a link to a simple svg drawing widget built with closure
http://webos-goodies.googlecode.com/svn/trunk/blog/articles/make_a_drawing_tool_with_closure_library/simple-draw.js

Categories