在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> <h3>canvas:显示组合图形</h3> <!-- 创建一个下拉列表来让用户选择按照什么方式来组合图形 --> <!-- 一旦用户做出了选择,就会触发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是蓝色正方形(旧图形)
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。