======================================================
注:本文源代码点此下载
======================================================
我自己有个毛病:微软不大张旗鼓支持的技术我就不去尝试,等微软一说要支持了我就要尝试了。可能是跟着微软的路线走习惯了吧,不过想想挺傻的。
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 html5p>
canvas>
div>
有经验的同学可能一看这html5代码就知道这注定是个悲剧,当有img元素在canvas下面时,不管怎样canvas就是不透明,忘记了canvas上可不可以画上东西了,应该也是不行的。看来这canvas元素有“洁癖”,不愿和其他低级元素同流合污。就算我要退而求其次,作为cantainer的背景元素出现都不行。我的感觉是这个canvas可能不会对其他元素透明的。所以上面的代码其实是错误的代码...
那怎么样才能实现类似photoshop里图层的效果呢?那就是多弄几个canvas元素,把上面的img换成canvas,然后把img绘制到这个canvas上,这样canvas对canvas就是透明的了。哎...代码如下:
some info to tell the people whose broswer doesn't support html5
好了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下不会这样
未完待续....
======================================================
在最后,我邀请大家参加新浪APP,就是新浪免费送大家的一个空间,支持PHP+MySql,免费二级域名,免费域名绑定 这个是我邀请的地址,您通过这个链接注册即为我的好友,并获赠云豆500个,价值5元哦!短网址是http://t.cn/SXOiLh我创建的小站每天访客已经达到2000+了,每天挂广告赚50+元哦,呵呵,饭钱不愁了,\(^o^)/