组合合并canvas图形
在HTML5中有11种组合图形的方式,只要把他们设置到context.globalCompositeOperation中就可以了,下面是一些证明各种图形组合方式的结果的示例。
HTML代码很简单,就2个控件,一个是下拉列表,让用户选择组合方式,并且一旦用户做出了选择,就执行js函数draw(id),从而在第二个控件canvas上根据用户当前选择的组合方式进行画图。第二个控件就是一个canvas,用于显示画图的内容。
<!DOCTYPE html> <head> <meta charset="UTF-8"> <title>HTML5 Combine Shape DEMO</title> <script type="text/javascript" src="js/drawCombinedShape.js"></script> </head> <body></body> <h2>canvas:显示组合图形</h2> <!-- 创建一个下拉列表来让用户选择按照什么方式来组合图形 --> <!-- 一旦用户做出了选择,就会触发onchange处理函数,于是调用js函数,让其在canvas组件上画图 --> <select id="selectCombineMethod" onchange="draw('canvas')"> <option >source-atop</option> <option>source-in</option> <option>source-out</option> <option>source-over</option> <option>destination-atop</option> <option>destination-in</option> <option>destination-out</option> <option>destination-over</option> <option>lighter</option> <option>copy</option> <option>xor</option> </select> <br><br> <!-- 指定一个canvas元素用于显示结果 --> <canvas id="canvas" width="1000” height="1000"/> <br><br>
js函数就是负责响应下拉列表的onchange事件从而在canvas上画图,它先绘制原图形(distination,在这里是一个蓝色正方形),然后取得用户选择的组合方式,再根据此方式画出新图形(source,在这里是一个红色的圆):
/** * This file is confidential by Charles.Wang * Copyright belongs to Charles.wang * You can make contact with Charles.Wang (charles_wang888@126.com) */ function draw(id){ //得到用户选择的图形组合选项: var selectComponent=document.getElementById("selectCombineMethod"); //取得用户的选择的索引 var selectedIndex =selectComponent.selectedIndex; //得到用户的选择的值,也就是选择的图形组合策略 var selectedCombinedStrategy = selectComponent.options[selectedIndex].value; //得到页面上的画布对象 var canvas=document.getElementById(id); if(canvas ==null) return false; var context = canvas.getContext('2d'); //画原来的图形,蓝色正方形 context.fillStyle="blue"; context.fillRect(40,40,60,60); //将用户选择的图形组合方式设定到context中 context.globalCompositeOperation=selectedCombinedStrategy; //画新图形,是一个红色的圆 //这时候,context会根据图形的组合策略来决定如何绘制这2个图形 context.beginPath(); context.fillStyle="red"; context.arc(40+60,40+60,30,0,Math.PI*2,false); context.fill(); }
实验可以根据你用户的选择来显示不同结果:这里的source是红色的圆(新图形),distination是蓝色正方形(旧图形)
- source-atop=新图形中(新 and 老)+老图形中(!(新 and 老))
- source-in=新图形中(新 and 老)
- source-out=新图形中(!(新 and 老))
- source-over(默认值)=老图形中(!(新 and 老))+新图形中(全部)
- destination-atop=老图形中(新 and 老)+新图形中(!(新 and 老))
- destination-in=老图形中(新 and 老)
- destination-out=老图形中(!(新 and 老))
- destination-over=老图形中(全部)+新图形中(!(新 and 老))
- lighter=老图形中(!(新 and 老))+ 新图形中(!(新 and 老))+新 and 老(色彩叠加)
- copy=新图形中(全部)
- xor(对称差)=老图形中(!(新 and 老))+新图形中(!(新 and 老))
本文出自 “平行线的凝聚” 博客,请务必保留此出处http://supercharles888.blog.51cto.com/609344/854073
加支付宝好友偷能量挖...