IE9下html5初试小刀

2020-04-22 07:30:55易采站长站整理

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://huoche.7234.cn/images/jb51/u041uaif0w5.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) {