I'm using Script# inside Visual Studio 2010 to import the API for the HTML5 Canvas element.
Its working great for things like FillRect(), MoveTo(), LineTo() and so on. I've declared the following interface and then I can code against it in C#. Then, Script# converts it to JavaScript nicely.
public interface ICanvasContext
{
void FillRect(int x, int y, int width, int height);
void BeginPath();
void MoveTo(int x, int y);
void LineTo(int x, int y);
void Stroke();
void FillText(string text, int x, int y);
}
I want to include the StrokeStyle property that takes a simple string, but I don't see how to do this with an interface. The following interface properties create a prefix in the JavaScript, which causes it to fail. The resulting JavaScript will not match the HTML5 Canvas API.
string StrokeStyle { get; set; }
string Font { get; set; }
The previous property wil开发者_运维百科l create this JavaScript:
ctx.set_strokeStyle('#FF0');
How can I get Script# to generate the simple assignment properties of the canvas context without the get_/set_ prefix?
Got it! I was using an interface, which is fine for some cases, but when I needed the field, I had to switch to an abstract class so as not to get the compilation error.
public abstract class Canvas : DOMElement
{
public abstract CanvasContext GetContext(string dimension);
}
public abstract class CanvasContext
{
public abstract void FillRect(int x, int y, int width, int height);
public abstract void BeginPath();
public abstract void MoveTo(int x, int y);
public abstract void LineTo(int x, int y);
public abstract void Stroke();
public abstract void FillText(string text, int x, int y);
public string StrokeStyle;
public string Font;
}
Those two abstract classes let me use the HTML5 Canvas API from Script#, like so:
public class MySample
{
public void DoWork(string canvasId)
{
Canvas canvas = (Canvas) Document.GetElementById(canvasId);
CanvasContext ctx = canvas.GetContext("2d");
// ctx.FillRect(10,20,100,300);
ctx.BeginPath();
ctx.MoveTo(10, 10);
ctx.LineTo(100, 300);
ctx.MoveTo(20,10);
ctx.LineTo(559,300);
ctx.StrokeStyle = "#F00";
ctx.Stroke();
}
}
One quick note -
With script# 0.6, which is now public and available for download off of http://projects.nikhilk.net/ScriptSharp, you'll see Canvas APIs out-of-the-box in Script.Web.dll.
Hope that helps.
Change the property into a simple field and it should work fine..
IE:
public string StrokeStyle;
public string Font;
It infers and generates the get_
/ set_
for property values.
精彩评论