www.thedatafarm.com
Julia Lerman
Exploring Silverlight's InkPresenter object
Aug 2007: Updated for Silverlight 1.0 Release Candidate
[using Safari? Read this blog post first...]

           Next




I began by using a Silverlight InkPresenter canvas in the XAML embedded onto an HTML page.


Note that I am using the Silverlight Beta 1.0 with GoLive license. This version does NOT have the .NET runtime in it. Starting with v 1.1 it does.

Unlike previous means of embedding ink on the web, this is browser friendly and can be used on a Mac and a PC. If you have a tablet, then you get to use your stylus. If you don't then you can draw with your mouse.

The key code chunks for creating this page are below.




THE CODE

Embedding CreateSilverlight in HTML

<div id="MySilverlightHost">
   <script type="text/javascript">
      CreateSilverlight();
   </script>
</div>

CreateSilverlight.js
(updated for RC)

function createSilverlight()

 Silverlight.createObject(
   "xaml/MyInkCanvas.xaml",
    MySilverlightHost,
    "wpfobj",
    {width:'400', height:'200', inplaceInstallPrompt:false,
      background:'lightgray', isWindowless:'false', framerate:'36', version:'1.0'},
    {onError:null, onLoad:null}, null);


MyInkCanvas.xaml
(updated for RC)
<!--this  does not include the addition of the pen image-->

<Canvas xmlns="http://schemas.microsoft.com/client/2007"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="javascript:root_Loaded"
        x:Name="root"
        Width="800" Height="400">

<InkPresenter x:Name="inkPresenterElement"
              Background="transparent" Width="800" Height="400"
              MouseLeftButtonDown="InkPresenterMouseDown"
              MouseMove="InkPresenterMouseMove"
              MouseLeftButtonUp="InkPresenterMouseUp"/>
</Canvas>

ink.js  (from Gavin Gear at Microsoft)

var wpf;
var inkPresenter; // Corresponds to InkPresenter element in xaml
var newStroke = null; // The Stroke variable we’ll use here in mouse handlers var currentColor=\"#FF000000\"; //black

function root_Loaded(sender, args) 
{
    wpf = document.getElementById(\"wpfobj\");
    inkPresenter = sender.findname(\"inkPresenterElement\");
}

// Capture mouse and create the stroke
function InkPresenterMouseDown(sender,args)

   inkPresenter.CaptureMouse();
   newStroke = wpf.content.createFromXaml(\'<Stroke/>\');
   newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   newStroke.DrawingAttributes.Color=currentColor;
   inkPresenter.Strokes.Add(newStroke);
}

// Add the new points to the Stroke we’re working with
function InkPresenterMouseMove(sender,args) 
   if (newStroke != null)
   {
      newStroke.StylusPoints.AddStylusPoints(args.GetStylusPoints(inkPresenter));
   }
}

// Release the mouse
function InkPresenterMouseUp(sender,args) 
{
   newStroke = null;
}