I'm trying to create a box on canvas that reacts to MouseClick events using Dart and StageXL. My code is as follows:
import 'dart:html' as html;
import 'package:stagexl/stagexl.dart' as sxl;
void main() {
var canvas = html.querySelector('#canvas');
setCanvasFullScreen(canvas);
var stage = new sxl.Stage(canvas);
var renderLoop = new sxl.RenderLoop();
renderLoop.addStage(stage);
var rect = new sxl.Shape();
rect.graphics.rect(80, 50, 100, 100);
rect.graphics.fillColor(sxl.Color.Crimson);
// rect.on(sxl.MouseEvent.CLICK).listen(react);
rect.addEventListener(sxl.MouseEvent.CLICK, react);
stage.addChild(rect);
}//end main
void react(sxl.MouseEvent event){
var w = html.window;
w.alert("I'm clicked!");
}//end onClick
void setCanvasFullScreen(canv) {
var w = html.window;
// w.alert("Holla!!!");
int _width = w.innerWidth as int;
int _height = w.innerHeight as int;
canv.setAttribute('width', '$_width');
canv.setAttribute('height', '$_height');
}
I've tried both on(MouseEvent.CLICK).listen(react); and addEventListener(MouseEvent.CLICK, react); without success there is no reaction. I'm using Dart Editor & SDK version 1.8.5 and debugging on the default Dartium browser.
Any help is appreciated.
After some search on the internet I found this link on StageXL forum that properly explained why it did not work. So I've changed the line:
var rect = new sxl.Shape();
to:
var rect = new sxl.Sprite();
and it reacts nicely.
Hope this is helpful to someone.
Related
I'm trying to add barcode scanner feature to my xamarin.ios app. I'm developing from visual studio and I've added the Zxing.Net.Mobile component from xamarin components store.
I've implemented it as shown in the samples:
ScanButton.TouchUpInside += async (sender, e) => {
//var options = new ZXing.Mobile.MobileBarcodeScanningOptions();
//options.AutoRotate = false;
//options.PossibleFormats = new List<ZXing.BarcodeFormat>() {
// ZXing.BarcodeFormat.EAN_8, ZXing.BarcodeFormat.EAN_13
//};
var scanner = new ZXing.Mobile.MobileBarcodeScanner(this);
//scanner.TopText = "Hold camera up to barcode to scan";
//scanner.BottomText = "Barcode will automatically scan";
//scanner.UseCustomOverlay = false;
scanner.FlashButtonText = "Flash";
scanner.CancelButtonText = "Cancel";
scanner.Torch(true);
scanner.AutoFocus();
var result = await scanner.Scan(true);
HandleScanResult(result);
};
void HandleScanResult(ZXing.Result result)
{
if (result != null && !string.IsNullOrEmpty(result.Text))
TextField.Text = result.Text;
}
The problem is that when I tap the scan button, the capture view is shown correctly but if I try to capture a barcode nothing happens and it seems the scanner doesn't recognize any barcode.
Someone has experienced this issue? How can I made it work?
Thanks in advance for your help!
I answered a similar question here. I couldn't get barcodes to scan because the default camera resolution was set too low. The specific implementation for this case would be:
ScanButton.TouchUpInside += async (sender, e) => {
var options = new ZXing.Mobile.MobileBarcodeScanningOptions {
CameraResolutionSelector = HandleCameraResolutionSelectorDelegate
};
var scanner = new ZXing.Mobile.MobileBarcodeScanner(this);
.
.
.
scanner.AutoFocus();
//call scan with options created above
var result = await scanner.Scan(options, true);
HandleScanResult(result);
};
And then the definition for HandleCameraResolutionSelectorDelegate:
CameraResolution HandleCameraResolutionSelectorDelegate(List<CameraResolution> availableResolutions)
{
//Don't know if this will ever be null or empty
if (availableResolutions == null || availableResolutions.Count < 1)
return new CameraResolution () { Width = 800, Height = 600 };
//Debugging revealed that the last element in the list
//expresses the highest resolution. This could probably be more thorough.
return availableResolutions [availableResolutions.Count - 1];
}
I found just what I needed to determine the dimensions of a div in Dart here
In short, it says:
Experimental
CssRect get borderEdge
Access the dimensions and position of this element's content + padding + border box.
How do code this?
I'm trying to use it with this variable:
import 'dart:html' as dom;
dom.DivElement textSpan = new dom.DivElement()
I found this example:
CssRect get borderEdge => textSpan.borderEdge;
My IDE (PHPStorm) throws up on it. I'm a Dart noob so I may be missing something obvious. Here's a screen shot:
I also get a build error:
Compiling citation|web/main.dart...
[Error from Dart2JS on citation|web/main.dart]:
packages/citation/tooltip/tooltip.dart:68:5:
Expected ';' after this.
CssRect get borderEdge => textSpan.borderEdge;
^^^^^^^
[Info from Dart2JS]:
Took 0:00:04.330468 to compile citation|web/main.dart.
Build failed.
I installed the Dart Editor and open the program in it. It didn't like it either:
tooltip.dart
This started out as the tooltip component from the Angular Dart Chapter 4 Tutorial
library tooltip;
import 'dart:html' as dom;
import 'package:angular/angular.dart';
#Decorator(selector: '[tooltip]')
class Tooltip
{
final dom.Element element;
#NgOneWay('tooltip')
TooltipModel displayModel;
dom.Element tooltipElem;
dom.Element entry; // Bibliographic entry: div in the index.html
Tooltip(this.element)
{
element..onMouseEnter.listen((_) => _createTemplate())
..onMouseLeave.listen((_) => _destroyTemplate());
}
void _createTemplate()
{
assert(displayModel != null);
tooltipElem = new dom.DivElement();
// All entries have the id 'bex' where x is an integer
entry = dom.querySelector('#be${displayModel.entryRef.toString()}');
String htmlText = entry.innerHtml;
if (displayModel.entryRef != null)
{
dom.DivElement textSpan = new dom.DivElement()
..appendHtml('<hr>')
..appendHtml(htmlText)
..style.color = "black"
..style.fontSize = "smaller"
..style.paddingBottom = "5px";
tooltipElem.append(textSpan);
}
int entryWidth = 200;
tooltipElem.style
..padding = "5px"
..paddingBottom = "0px"
..backgroundColor = "#FFF5E0"
..borderRadius = "5px"
..width = "${entryWidth}px";
// position the tooltip.
int windowHeight = dom.window.innerHeight;
int windowWidth = dom.window.innerWidth;
var elTopRight = element.offset.topRight;
var elBottomLeft = element.offset.bottomLeft;
int height = 100;
int top = elTopRight.y;
int bottom = elBottomLeft.y;
int left = elBottomLeft.x;
int right = elTopRight.x;
CssRect get borderEdge => textSpan.borderEdge;
print('borderEdge:$borderEdge');
// See if it will fit above
int y = top - height - 10;
if (y < 0) y = bottom + 10; // If it doesn't fit, put it below
// Start with the left
int x = left;
tooltipElem.style
..position = "absolute"
..top = "${y}px"
..left = "${x}px";
// Add the tooltip to the document body. We add it here because we need to position it
// absolutely, without reference to its parent element.
dom.document.body.append(tooltipElem);
}
void _destroyTemplate()
{
tooltipElem.remove();
}
}
class TooltipModel
{
final int entryRef;
TooltipModel(this.entryRef);
}
Answer
This summarizes Günter Zöchbauer's answer in the comments and an answer of my own.
The first problem was that I was using the wrong syntax given the location of the code. The correct code for this location is:
CssRect borderEdge = tooltipElem.borderEdge;
The second problem unique to my situation was that my import statement was declared as:
import 'dart:html' as dom;
The 'as dom' requires me to prefix all html api references with dom. So in my case, I needed to code:
dom.CssRect borderEdge = tooltipElem.borderEdge;
I got this code from the Angular dart tutorial. My next step is to remove that prefix so it doesn't screw me up again. Also note the answer code uses tooltipElem instead of textSpan. That change has nothing to do with the fix to the problem.
I tried and it works just fine (I'm using Dart bleeding edge/nightly build)
I've developed simple project using three.dart framework. It launches and shows web page ok. But after 3-5 seconds it crashes with unknown error. Dart editor and browser don't show the reason why it crashed
Here is a code:
import 'dart:html';
import 'dart:math' as Math;
import 'package:three/three.dart';
class MyClass {
Element container;
PerspectiveCamera camera;
Scene scene;
CanvasRenderer renderer;
Mesh plane;
num targetRotation;
num targetRotationOnMouseDown;
num windowHalfX;
num windowHalfY;
var evtSubscriptions = [];
void run() {
init();
animate(0);
}
void init() {
targetRotation = 0;
targetRotationOnMouseDown = 0;
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
container = new Element.tag('div');
document.body.nodes.add( container );
Element info = new Element.tag('div');
info.style.position = 'absolute';
info.style.top = '10px';
info.style.width = '100%';
info.style.textAlign = 'center';
info.innerHtml = 'Drag to spin the cube';
container.nodes.add( info );
scene = new Scene();
camera = new PerspectiveCamera( 70.0, window.innerWidth / window.innerHeight, 1.0, 1000.0 );
camera.position.y = 150.0;
camera.position.z = 500.0;
scene.add( camera );
// Plane
plane = new Mesh( new PlaneGeometry( 200.0, 200.0 ), null);
scene.add( plane );
renderer = new CanvasRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
container.nodes.add( renderer.domElement );
}
void render() {
renderer.render( scene, camera );
}
animate(num time) {
window.requestAnimationFrame(animate);
render();
}
}
void main() {
new Canvas_Geometry_Cube().run();
}
How to fix a crash?
I found out the problem. It works with Web GL properly (NOT canvas).
Sergio three.dart might need some work to be updated, its been awhile since a latest version was published on pub. Sorry. Please feel free to checkout the latest branch or code review on the https://github.com/threeDart/three.dart site
Why does this example, (from adobe.com) work in Chrome, but not in FF and IE?:
does not work = I can see the permission window, but when I click 'allow' all I see is a blank white screen.
http://wonderfl.net/c/7624
or see code below:
// frame action
import flash.media.Microphone;
import flash.events.SampleDataEvent;
import flash.utils.ByteArray;
import flash.display.Graphics;
var nWidth:Number = stage.stageWidth;
var nCenter:Number = stage.stageHeight / 2;
var nScale:Number = 100;
var myGraphics:Graphics = graphics;
var my_mic:Microphone = Microphone.getMicrophone();
my_mic.rate = 22;
my_mic.gain = 100;
my_mic.addEventListener(SampleDataEvent.SAMPLE_DATA, drawSampleData);
function drawSampleData(eventObject:SampleDataEvent):void
{
var myData:ByteArray = eventObject.data;
myGraphics.clear();
myGraphics.lineStyle(0, 0x000000);
myGraphics.moveTo(0, nCenter);
var nPitch:Number = nWidth / myData.length;
while (myData.bytesAvailable > 0)
{
var nX:Number = myData.position * nPitch;
var nY:Number = myData.readFloat() * nScale + nCenter;
myGraphics.lineTo(nX, nY);
}
}
Thanks.
I tried the example in the link you included and it did not work in any of my browsers, Chrome included.
The source code in the link you have included shows most of your code (including a few imports) nested inside a function called FlashTest, in my experience I cannot understand why this would even run in Chrome.
I'm trying to develop an app for iOS using flash CS6. I have imported an image using a loader. I now want to be able to create a duplicate instance of the loaders bitmap data and have been trying:
var my_loader:Loader = new Loader();
my_loader.load(new URLRequest("cats.jpg"));
my_loader.scaleX = 0.2;
my_loader.scaleY = 0.2;
addChild(my_loader);
var duplicationBitmap:Bitmap = new Bitmap(Bitmap(my_loader.content).bitmapData);
duplicationBitmap.x = 300;
duplicationBitmap.y = 300;
addChild(duplicationBitmap);
Unfortunately when I test the code it doesn't work. I get the initial loaded image but not the duplicate, I also get an output error of:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Main()
Any ideas would be greatly appreciated.
Bitmap(my_loader.content) is a DisplayObject, not neccessary a Bitmap, that gives you the nullpointer error.
For copying bitmapData, you should use BitmapData.clone().
You can draw the loader on to a BitmapData object when the loader initializes, then simply use it to create as many Bitmap objects as you need when the loader completes.
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.events.Event;
var loaderBitmapData:BitmapData;
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.INIT, loaderInitEventHandler);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteEventHandler);
loader.load(new URLRequest("eXO-01.png"));
function loaderInitEventHandler(event:Event):void
{
loader.contentLoaderInfo.removeEventListener(Event.INIT, loaderInitEventHandler);
loaderBitmapData = new BitmapData(event.target.width, event.target.height);
loaderBitmapData.draw(event.target.loader as Loader);
}
function loaderCompleteEventHandler(event:Event):void
{
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loaderCompleteEventHandler);
createBitmaps();
}
function createBitmaps():void
{
var image1:Bitmap = new Bitmap(loaderBitmapData);
image1.scaleX = image1.scaleY = 0.2;
var image2:Bitmap = new Bitmap(loaderBitmapData);
image2.scaleX = image2.scaleY = 0.4;
image2.x = image2.y = 100;
addChild(image1);
addChild(image2);
}