Emil’s Chronicle - The journal of Emil A Eklund

Canvas in IE

Since Apple’s introduction of canvas earlier this year support for it has been added to both Mozilla and Opera, making it more widespread than, the much older, SVG. I suspect that’s largely due to the complexity of the later and the simplicity of canvas. However it still cannot see widespread deployment as it’s not supported by Internet Explorer, which has around 80-90% of the browser market.

IE doesn’t support SVG natively either, it does support something called VML though, and it’s been around since the 5.0 days, if I remember correctly.
VML does pretty much the same thing as SVG (as far as basic drawing is concerned).

Using VML, in combination with behaviors, it should therefor be possible to emulate a subset of SVG or Canvas in IE. That’s the idea I got a few days ago when working on a basic drawing abstraction, and according to Google a few others have thought along those lines as well. Couldn’t find any actual implementation though so I decided to make my own, how hard could it be?

If such implementation could be created it would open up the world of client side drawing to web site developers and allow all kind of neat widgets to be developed.

Having spent a few evenings working on such an implementation I’ve managed to create a proof of concept:
- Demo
- Directory index

As of now the supported methods are; arc, beginPath, closePath, fill, fillRect, lineTo, moveTo, rect, restrore, rotate, save, stroke, strokeRect and translate.
Rotate only works if the origin is set to the the default value (0,0 - upper left corner)

As far as attributes goes, the only ones honored are; fillStyle, globalAlpha, lineWidth and strokeStyle.

It’s still work in progress and all functionality is not yet supported or doesn’t work correctly, however the basic functionality is there, and it looks promising.

86 Responses to 'Canvas in IE'

  1. Dean Edwards Says:

    Fantastic work! I’ve been looking at implementing something similar - you beat me to it. :-)

  2. Sebastian Werner Says:

    Great work!

    The problem probably could be the performance. If you sometimes have the implementation complete, it may be simply too slow for real-world-usage. Mozilla’s canvas outperformes IE’s version probably by factor 10 here.

    Keep up the good work.

  3. Ajaxian Says:

    Canvas in IE

    As soon as we saw SVG, Ben thought that it would be quite possible to take the VML support that IE has had for a long time, and make a converter that would make a subset of SVG work in…

  4. Julien Couvreur Says:

    I’m confused: from what I understand you implemented canvas on top of VML. I don’t see where SVG is involved in this.

  5. Emil Says:

    Julien Couvreur: SVG is not involved here, just mentioned it as a competing technology. It should however be possible to implement a subset of SVG (Tiny) in a similar fashion.

  6. Karl G Says:

    Exciting! Canvas based charting libs here we come.

  7. Dave Hoover Says:

    Emil, this is great stuff!

    I tried using your canvas.js and canvas.htc on my Ajax Trains example (http://redsquirrel.com/dave/play/ajaxtrains.html) but I saw nothing in IE. It looks like you haven’t implemented the drawImage canvas method (no complaints). But I expected at least to see the tracks and I’m wondering why I don’t see them. Anything come to mind?

  8. Emil Says:

    Dave: Make sure the htc file is served with the correct content type, ie is sensitive about that when it comes to behaviors (but mostly ignores them elsewhere). You’re right about drawImage, it’s not implemented, yet.

  9. CanvasGame Says:

    I see that you have chosen to create ‘IECanvasContext’ as your rendering object, I suggest you rename it to ‘CanvasRenderingContext2D’ to coincide with the whatwg specification.

  10. Nick Says:

    Any info on getting canvas element to print wysiwyg.

  11. Manish Jethani Says:

    Hey, nice work! I was thinking of implementing something similar in Flash (for IE) but gave up after running into a some issues.

  12. Kermit@CS Says:

    Happy New Year

    Just wanted to wish everyone a really great [civilian] new year
    Went out last night - I think this was the first time I actually enjoyed myself on new years eve. I was at the Syndrome, which quite surprisingly wasn’t packed full - and there…

  13. links for 2006-01-02 at protocol7 Says:

    […] Canvas in IE A Javascript/VML implementation of that works in IE (tags: javascript canvas SVG vml)

  14. IE Canvas : Mo Jebus Says:

    […] Emil is creating a script to make canvas work in IE. […]

  15. browsing.ru » Blog Archive » IE & canvas Says:

    […] Эмиль Эклунд написал эмулятор canvas для Internet Explorer. Небольшой скрипт при помощи VML реализует поддержку базовой функциональности canvas, его работу можно увидеть на демонстрационной странице. […]

  16. sly Says:

    Error:

    iecanvas.htc:

    Bad:
    IECanvasContext.prototype.stroke = function() {
    […]
    o.weight = this.lineWidth;
    […]

    Good:
    IECanvasContext.prototype.stroke = function() {
    […]
    o.strokeweight = this.lineWidth;
    […]

  17. erik’s weblog » Blog Archive » Emil is on Fire Says:

    […] Emil has been really active lately. Not only did he emulate canvas in IE, he also used it to create a slick charting control for WebFX. […]

  18. slyi Says:

    This seems pretty fast in IE, would you have any brenchmarks against FF and IE?

  19. Emil Says:

    slyi: Did a simple performance test using the first chart on the chart component demo page. Created it ten times and timed the draw function.

    The average time was just under 6 times higher in IE than in Mozilla. For the ie canvas demo the figure is closer to 7.

  20. Patrick Corcoran Says:

    Good stuff.

    I implemented a similar library a couple of weeks ago. One problem I noticed, which I see you suffer from also, is that the colors are not identical across platforms. If you view the IE sample next to the Firefox sample, you can see that the colors in the IE version appear more washed out.

    Let us know if you ever find any logic behind this or any way to compensate.

    Cool hack, though, congrats.

  21. Emil Says:

    Patrick: What version of ie and firefox are you using? The colors are either identical or differs with a single step for each channel (rgb) for me.

  22. Julien Couvreur Says:

    Is there a way to make the initialization automatic?
    Removing the initialization code (see below) would make Canvas/FF and Canvas/IE look closer.

    “window.onload = function() { ieCanvasInit(); }”

  23. Julien Couvreur Says:

    I was modifying the CanvasGraph library to run on top of IECanvas, but ran into a possible bug. The “arc” method appears to be slightly different than the one in Firefox: the portion of circle that got drawn was the complement of what got rendered in IE.
    Say for example, I draw a quarter circle with arc, IECanvas would actually render a three-quarter circle.
    My workaround was to switch the startAngle and endAngle.

  24. rickman Says:

    And what about the drawWindow function ? are you intending to develop it ?

  25. Erik Arvidsson Says:

    drawWindow is a Firefox extension. It is really nice, maybe the old IE HTML thumbnail ActiveX control could be used to some extent?

    There are other things that cannot be effiently emulated like the toDataURL() method.

  26. Fotis Evangelou Says:

    Hello Emil,

    there is this excellent script from Cow’s Blog in:
    http://cow.neondragon.net/stuff/reflection/

    It basically uses the canvas tag and some javascript wizardry to produce image reflections, but only in browsers that support this tag, like firefox or safari.

    Could your implementation of the “ie canvas tag patch” be “hooked” to such a script or any other script that uses the canvas tag (to “draw” stuff inside the html page) and therefore act as a converter?

    Now, that would be a neat feature, wouldn’t it?

  27. Erik Arvidsson Says:

    The reflection script is a really nice use of the canvas tag. I believe this can be emualted in IE using the Compose filter.

  28. rickman Says:

    Image reflections is easier to render in IE, using a combination of filters like this :

    1. Original image

    2. Reflect

  29. Fotis Evangelou Says:

    Thans Eric and rickman for your replies, however could you be a little more specific.

    You see, my knowledge for javascript I’m afraid is limited to the include in the html template! How could these two techniques be combined?

    Thanks in advance for any response.

  30. rickman Says:

    I’m sorry Fotis but it seems that my comments in this thread can’t include html tags and javascript.

  31. Matt Says:

    Great code, great work! I made a couple of changes to fix some bugs and annoyances so I thought that I should post them:

    ADDED: a clearAll method. Not supported by Gecko, but as VML cannot easily support clearRect I needed something. There is probably a better way to do this…
    IECanvasContext.prototype.clearAll = function() { element.innerHTML = “”; };
    FIXED: bug in arc method, some args not converted to int which caused scary things to happen and occasional crashes. Using Math.round on x1, x2, x3, x4, y1, y2, y3 and y4.
    MODIFIED: moveTo and lineTo to use Math.round rather than parseInt to avoid rounding errors.
    For example: parseInt(’5.9′) => 5 and Math.round(’5.9′) => 6
    FIXED: stroke method to use o.strokeWeight = this.lineWidth; instead of o.weight = this.lineWidth; ala Sly’s comment on Emil’s site. Thanks, Sly.

  32. Emil Says:

    Math, sly: Thanks, I’ll post an update shortly!

  33. pagameba Says:

    This is awesome, looking forward to the update. One question … has anyone tried using this with dynamically created canvases? I am creating a canvas using document.createElement on demand, which works in Safari and Firefox, but in IE the canvas doesn’t work … it seems canvas.context is defined and something like canvas.context.fillStyle has the correct inital value, but neither the canvas nor the context have methods so canvas.getContext() doesn’t work (for instance). Help please!!!

  34. pagameba Says:

    further to my last comment … duh! this makes sense I think. After doing document.createElement(’canvas’), the behaviour is not applied for some non-trivial amount of time so called getContext is invalid until the behaviour has been applied. Not sure if the thread of execution blocks this until control is returned to the browser or not. In any case, by redesigning so my canvas is created early on, and the context is retrieved at some later time, it works.

  35. Arthur Says:

    this is really cool.. by any chance, do you have an update yet?

  36. 網絡暴民 Jacky’s Blog » 20060103網摘 - 06趨勢 Says:

    […] Canvas in IE 使用 VML 加上 behaviours 來在 IE 上模擬 Canvas […]

  37. Mark Finkle’s Weblog » Blog Archive » SVG in IE Says:

    […] Inspired by Emil’s emulation of the canvas tag in IE, I put together a simple SVG emulation behavior for IE. As with Emil’s code, I am making use of Internet Explorer’s VML support. The behavior will walk the SVG element structure and attempt to convert to appropriate VML elements. It’s far from complete, but it does a decent job. Supported features include: […]

  38. Charles Says:

    Could anybody please tell me what is the fastest way to plot 2D graphics in IE currently?

  39. KevLinDev Blog » Blog Archive » JSDrawing Now Supports VML Says:

    […] I was reading through some of today’s posts over at svg-developers and I came across Mark Finkle’s blog post about his SVG in IE project. He has a nice demo showing a client-side conversion of SVG to VML via behaviors. In an earlier post, he mentions that he was inspired by Emil Eklund’s Canvas in IE project. (It seems like everyone’s transcoding these days). I had been wanting to add VML as a supported renderers, so with the help of these two fine examples, I added VML support today: […]

  40. erik’s weblog » Blog Archive » ExplorerCanvas Says:

    […] Emil’s initial implementation uses a behavior. However, the canvas tag is not recognised in IE so you get a invalid DOM. The ExplorerCanvas does not use a behavior and it only uses one js file. This makes it a bit simpler and allows more control over the element. Normally, the canvas elements are initialized when the page is loaded but if you want to create canvas elements on the fly (or use them before the page has loaded) the following code should work: […]

  41. ecrans veille Says:

    Nice Work!

    is very interesting

    THANKS

  42. logiciels telecharger Says:

    This seems pretty fast in IE, would you have any brenchmarks against FF and IE?

  43. webcams sexe Says:

    There are other things that cannot be effiently emulated like the toDataURL() method.

  44. Emil’s Chronicle » Chart 1.02 Says:

    […] I’ve update the WebFX Chart widget to use the new, and superior, ExplorerCanvas IE Emulation layer instead of my old IECanvas one. […]

  45. Anigozanthos Says:

    IE6 is technically very good…

    Over the last year or so, it’s occurred to me that IE6, in spite of it’s neglect since it was released in October 2001, is really an incredibly capable browser; much more powerful that any other in many ways.My reasoning is ……

  46. KillerSite Blog » Blog Archive » CANVAS DHTML: Draw Line, Ellipse, Oval, Circle, Polyline, Polygon, Triangle with JavaScript - Forget SVG! Says:

    […] http://me.eae.net/archive/2005/12/29/canvas-in-ie/ […]

  47. Christian Simms’s Botonomy Ramblings » Blog Archive » SVG vs. Canvas: Tastes Great, or Less Filling? Says:

    […] IE: of course it doesn’t support it. someone tried writing a small javascript emulator but that was just an experiment and not a real project […]

  48. Cameron Shorter Says:

    Emil,
    Nice work, why not release this as a project on sourceforge or similar?
    (Or has someone done this already?)

    What I’d like to see is a library which changes it vector rendering depending on the browser being used:
    IE: Use VML
    Later versions of firefox: use canvas
    Old browsers: Use wz_graphics

    (We need this for a Geographic Map rendering engine at http://communitymapbuilder.org )
    Has anyone looked into this?

  49. Emil Says:

    Cameron: It’s on sourceforge already, or rather ExplorerCanvas, which replaces Canvas in IE, is. See http://sourceforge.net/projects/excanvas

  50. Orion Says:

    This Canvas stuff is great

    Is is possible using the canvas to create a “screen shot”

    To save the content of a canvas as a .jpg or something of that nature

  51. Srinivas Says:

    Hi,
    My name is srinivas , i am developer , recently i had seen your graphs , i downloaded ur stuff and i was trying to execute in IE 6.0 but i am getting the error object not supported, Could you please help.But it is executing when i am seeing in online demo

    Regards
    Srinivasa Rao S
    Ph.No : 0919980132116

  52. Emil Says:

    Srinivas > Make sure your server is configurated to serve the HTC file with the correct content type. Also, you might want to look into ExplorerCanvas instead.

  53. srinivas Says:

    Thanks Emil,
    Finally , i got the output.Can u tell me is there any option for events to the individual part of the pie chart or tool tip for individual pie chart. Waiting for ur reply.
    Thanks & Regards
    Srinivasa Rao. S

  54. Emil Says:

    Srinivas > Glad it worked out for you.

    As canvas is raster based, rather then vector based, no method for assigning events to shapes is present. However by analysing the mouse coordinate the “active” portion of the shape can be calculated and an event could be triggered.

  55. limalimon.com.es Says:

    […] http://ponderer.org/download/canvas_demo/ simulación de la etiqueta canvas para ie tutorial sobre canvas en mozilla developer center 02/08/2006 desarrollo web ¡Comenta! […]

  56. Roberto Asyn Says:

    Hello.
    My first 2 webpage at my site was made with VML.
    I had a like VML.
    At the site a made a water fountain…
    Let me know your opinion.

    Thanks

  57. gudangberas » PlotKit Says:

    […] PlotKit supports both HTML Canvas and SVG, along with an emulated canvas for Internet Explorer. […]

  58. Sylvain AZARIAN Says:

    What a great job you’ve done ;+)

    I discovered your work from the OReilly book “Ajax in a nutshell”.

    I’ve two questions :
    - what is the equivalent constant value for the lineJoin property ?
    I’ve tried the string constant (for example ’round’) but it doesn’t work

    - About line width : setting

    ctx.lineWidth = 10 ;
    or
    ctx.lineWidth = ‘10′;

    doesn’t change anything… Still have a width of 1.

    Thks

  59. Light Says:

    wonderful work indeed. Thanks.

  60. Rob Eberhardt - Canvas in IE Says:

    […] This is just awesome: …Okay, so it’s a slightly ugly picture, why is it awesome? Read about it here: http://me.eae.net/archive/2005/12/29/canvas-in-ie/.  Basically, Emil Eklund of WebFX extended IE to support Canvas elements, the currently most-buzzed new technology in web browsers. […]

  61. raj Says:

    I am not able to print the images drawn using canvas tag. Please let me why this is happening?

  62. shelly Says:

    Also check this out: www.cumulatelabs.com currently only works in IE, but we have plans for firefox soon!

  63. Software As She’s Developed » Blog Archive » Ajax/Javascript: 8 Ways to Create Graphics on the Fly Says:

    […] Use Canvas. Canvas was introduced in Safari and now in Firefox and Opera too. No sign of life in IE, but this there’s a fantastic hack (via Ajaxian) that emulates SVG using IE’s native VML support (more on VML below). […]

  64. Steve Says:

    Unless I’m missing something, this doesn’t work at all in IE7.

    that said, there is a lot of stuff that doesn’t work in IE7. :-(

  65. isong榮耀» a cool html element for picture.nice ^^ Says:

    […] 在指引下我去了Mozilla Developer Center去寻找传说中的canvas标签,他的原名称Canvas tutorial,粗略的看了一下使用的兼容性,使用的时候配合JavaScript脚本,在ff1.5以上可以直接使用,在ie下要加上 js 才能正常的 顯示效果。 […]

  66. KM Says:

    Hi,

    Your in IE work is just what I was looking for!

    As I’m trying to learn JavaScript, I used your work in a little tool that plots graphs of mathematical functions:
    http://home.scarlet.be/km/js/graph2.html

    Ultimatly I want to integrate this in a calculator I work on:
    http://home.scarlet.be/km/js/calc4.html

    Regards,
    K Moerman
    Belgium

  67. Eric Says:

    Emil,

    This works great but I am having a bit of an issue when I try to dynamically add canvas element.

    I am using plotkit to create graph based on criteria selected by the user. One of the shortfall of plotkit is that it doesn’t (yet) print the name of the series with the attached color so in order to do that I dynamically create a table with 2 column and as many rows as I have series and in each row I put the name and a canvas. This works great with firefox but in IE I can not get the 2d context for those canvas. Is there a way to get that working using excanvas.js?

    Thanks,
    Eric.

  68. Ted Says:

    How Do you really setup the use of canvas on IE7

  69. Mauricio Says:

    Amazing work!!! Congratulation emil!!
    and Steve i try in IE7, and i don´t have any problem.

    Regards.
    Mauricio from méxico.

  70. Acorda pra Web! » Jogos 3D em JavaScript Says:

    […] Por enquanto essa tag canvas só existe no Firefox e Safari, mas existe um jeitinho pra rodar tudo no Internet Explorer usando o VML (um avô do SVG). […]

  71. PlotKit: JavaScript Graph Plotting Library - News Says:

    […] PlotKit: JavaScript Graph Plotting Library PlotKit from Liquidx is a Javascript graph plotting library. It is aimed at web applications that require plotting series of data in modern web browsers. Here’s a quick run down of the features and sample output: PlotKit requires MochiKit. (1.3 or higher) PlotKit supports both HTML Canvas and SVG, along with an emulated canvas for Internet Explorer. PlotKit is easily extensible to include other rendering engines, styles and layouts. Please pursue the documentation for more information. PlotKit is licensed under the BSD license, so you can include it in your free or commercial applications without worrying. Road map features include: Point plots Defined Event System Support Animation support For more information, you can check out: Google Groups: plotkit PlotKit Quick Start tutorial Full documentation Published Sep 17 2006, 09:25 AM by AjaxMatters […]

  72. Wade Harrell Says:

    just found this today, although i was looking for it 6 years ago ;)
    http://www.xml.com/pub/a/2000/07/26/deviant.html

  73. Marc Pfeifhofer Says:

    @ Daniel:
    Why you can’t try it? I made just one and it wasn’t difficult.

    Or whar was your problem?

  74. Benak Says:

    I have a problem with ARC STYLE = PIESLICE, it’s render as CHORD style.
    Where could I insert or modify this parameter?

  75. David Says:

    Thank you for this fantastic work!

    I’ve come across a bug and was hoping someone could point me in the right direction. It seems that IE won’t render both a strokeStyle AND fillStyle when using the lineTo function.

    Example:

    var canvas = document.getElementById(’canvas’);
    var ctx = canvas.getContext(’2d’);

    ctx.fillStyle = ‘yellow’;
    ctx.strokeStyle = ‘red’;
    ctx.beginPath();
    ctx.lineWidth = 1;
    ctx.moveTo(1,1);
    ctx.lineTo(80,80);
    ctx.lineTo(100,20);
    ctx.closePath();
    ctx.stroke();
    ctx.fill();

    Only the stroke() function works. However, if I switch the order of the stroke() and fill() functions, then only fill() works. Any insight?

    Thanks!

  76. Emil Says:

    David: “Calling fill() or stroke() causes the current path to be used. To be filled or stroked again, the path must be recreated.”, see http://developer.mozilla.org/en/docs/Drawing_Graphics_with_Canvas

    Also, IECanvas is no longer maintained, it has been merged with, and superseded by, ExplorerCanvas, see http://me.eae.net/archive/2006/03/28/explorercanvas/

  77. Reflection Image Effect Script » article » kaizeku ban Says:

    […] Canvas in IE (VML) by Emil Eklund […]

  78. victorbos Says:

    Stumbled across your neat solution. Looks like it is just what I need. Thanks a bunch.

    BTW: Someone asked way back if there is a way to make the drawings appear automatically. The following works for me.

    “window.onload = function()
    { ieCanvasInit(); setTimeout(’draw()’,500); }”

    As I am new to this canvas (and iecanvas) is there a list of methods you’ve implemented, e.g., createLinearGradient(…) and createRadialGradient(…)?

  79. Ted Roper Says:

    Printing problem is not solved!!

    When you create an image using CANVAS it shows perfect in the screen and in the print preview, but when you print (both in PS and PCL printers it prints very small (about 100 px for an image of 600px-600px) and with incorrect colors.

    Is there a way to print canvas objects correctly?
    tks,
    ted

  80. indir Says:

    I have a problem with ARC STYLE = PIESLICE, it’s render as CHORD style.
    Where could I insert or modify this parameter?

  81. mark Says:

    What is the memory consamption of a canvas? If I paint an image on a canvas will it consume the same resources when loading the image as BMP file?

  82. indir Says:

    wonderful work indeed. Thanks.

  83. momoc_a » 又有新玩具:Canvas Says:

    […] canvas 是一个新的 html 元素,用来做为程序代码绘图的画布。而且 JavaScript 就能设定各项绘图指令。不过在 IE 下必须加载 这个 js 才能显示效果。 […]

  84. AlanH Says:

    Hi. Great work!

    I’ve just started trying to implement an animated game replay as a web service, using Canvas in FF/Safari. It’s pretty fast and effecitve, and I want to port it to IE.

    The excanvas.js library gets me some way there - I believe this was based on your work. However, the clearRect() only does a global clear. For major performance reasons, I really need to be able to clear previously drawn elements selectively, and then redraw those areas. Clearing the entire canvas and redrawing it from scratch gets painfully slow when trying to animate a complex view.

    I could probably get by if clearRect just deleted all existing elements that intersect the specified rectangle, or that are entirely contained within it. (with maybe even a mode switch to select which?). Is this feasible? I’ve had a quick look at the way the elements are set up in VML, and it seems there’s no easy way to delete an individual item in a path. Should I create separate canvasses for each component of the view, overlaid in each other, so that I can clear a specific canvas? How is page performance affected by having lots of overlaid canvasses?

    One other thing I found out - I had a CSS rule that applied to divs nested in the same parent as my canvas elements. That was overriding the CSS that excanvas defines for the VML div. It was easy to fix by making the CSS rule more explicit, but it may be worth noting for other users.

    Alan

  85. Graphical Representation on the Web « Vision + Design + Dev Says:

    […] The HTML canvas is become more and more popular for drawing charts but still in its infancy. Its not supported by IE even though there is a workaround to make it work in IE. It also doesn’t have the robustness to support the many different charting needs such as events on chart elements and chart element composition.  That said, if you are building serious charting controls, this is definitely not for you. […]

  86. Membuat Javascript Chart Tabulasi Pemilu 2009 - Ahmad Masykur Says:

    […] HTML5 telah didukung oleh sebagian besar browser modern seperti Firefox, Opera, Safari dan Google Chrome. Apakah IE juga telah mendukung HTML5? IE belum sepenuhnya mendukung HTML5. Dengan tidak adanya dukungan HTML5 pada IE, kita harus cari alternatif lain untuk menggambar pada IE. Caranya adalah dengan menggunakan Vector Markup Language yang didukung oleh IE. Untuk membuat chart saya gunakan library yang dapat diambil di http://www.jscharts.com/. […]

Leave a Reply

(required)
(required, will not be published)