ie9下html5初试小刀

我自己有个毛病:微软不大张旗鼓支持的技术我就不去尝试,等微软一说要支持了我就要尝试了。可能是跟着微软的路线走习惯了吧,不过想想挺傻的。

mvc是个好东西,为什么一入行的时候不去学一下,非要等到asp.net mvc出来了才去学;orm是个好东西,干嘛非要等到EF出来了才去学;html5是个好东西,干嘛非要等到IE9出来了才去学?......

——我想自己应该改掉这个坏毛病。

废话不多说了。

需求:模仿dreamweaver里为图片画上锚点的功能,生成html代码里的coords值的功能。

技术分析:直觉告诉我,html5 canvas可以胜任。

由于从来没实质性接触过canvas,只看过别人用canvas开发的demo,只好bing一下html5 canvas的教程咯。发现了下面的链接:http://kb.operachina.com/node/190

看完文档写代码:

代码分析:

1.1 html:要用一个图片作底,canvas放在它上面以供画图

1.2 css:你起码要位置放对、该透明的地方透明

1.3 javascript:鼠标事件要响应仨:mousedown,mousemove,mouseup

 

代码
<div id="container">
<img id="bg" width="390" height="560" src="http://www.sh1800.net/NavPic/20100917.jpg" />
<canvas id="drewpanel" width="390" height="560">
<p>some info to tell the people whose broswer doesn't support html5</p>
</canvas>
</div>

有经验的同学可能一看这html5代码就知道这注定是个悲剧,当有img元素在canvas下面时,不管怎样canvas就是不透明,忘记了canvas上可不可以画上东西了,应该也是不行的。看来这canvas元素有“洁癖”,不愿和其他低级元素同流合污。就算我要退而求其次,作为cantainer的背景元素出现都不行。我的感觉是这个canvas可能不会对其他元素透明的。所以上面的代码其实是错误的代码...

那怎么样才能实现类似photoshop里图层的效果呢?那就是多弄几个canvas元素,把上面的img换成canvas,然后把img绘制到这个canvas上,这样canvas对canvas就是透明的了。哎...代码如下:

 

<div id="container">
<canvas id="bg" width="390" height="560"></canvas>
<canvas id="drewpanel" width="390" height="560">
<p>some info to tell the people whose broswer doesn't support html5</p>
</canvas>
</div>

好了html算是搞定了,接下去就是往canvas上绘图,借助于javascript,这个任务非常简单。

 

 

window.addEventListener('load', function () {
  // Get the canvas element.
  var elem = document.getElementById('bg');
  if (!elem || !elem.getContext) {
    return;
  }

  // Get the canvas 2d context.
  var context = elem.getContext('2d');
  if (!context || !context.drawImage) {
    return;
  }

  // Create a new image.
  var img = new Image();

  // Once it's loaded draw the image on the canvas.
  img.addEventListener('load', function () {
    // Original resolution: x, y.
    context.drawImage(this, 0, 0);

    // Now resize the image: x, y, w, h.
    context.drawImage(this, 160, 0, 120, 70);

    // Crop and resize the image: sx, sy, sw, sh, dx, dy, dw, dh.
    context.drawImage(this, 8, 20, 140, 50, 0, 150, 350, 70);
  }, false);

  img.src = 'http://www.sh1800.net/NavPic/20100917.jpg';
}, false);
//直接在文档里拿下来的代码 请注意为了opera和ie9 onload事件是必须要的,不然图片会是一片空白,当然Chrome下不会这样

 

未完待续....

posted on 2010-09-18 10:32  ice6  阅读(1439)  评论(0编辑  收藏  举报

导航