使用canvas标签动态绘制图型,当点击鼠标时,以鼠标点击的坐标作为图形中心点。当点击数为偶数时画三角形,当点击数为奇数时画五角星
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title></title> <style type="text/css"></style> <script type="text/javascript"> var g=0; function getStyles(obj) { return document.defaultView.getComputedStyle(obj); } function getCanvasPos(canvas,e) { //获取鼠标在canvas上的坐标 var rect = canvas.getBoundingClientRect(); var leftB = parseInt(getStyles(canvas).borderLeftWidth);//获取的是样式,需要转换为数值 var topB = parseInt(getStyles(canvas).borderTopWidth); return { x: (e.clientX - rect.left) - leftB, y: (e.clientY - rect.top) - topB }; } function drawStar(context, r, R, x, y) { // 画五角星 context.beginPath(); for(var i=0;i<5;i++){ context.lineTo(Math.cos((18+i*75)/180*Math.PI)*R+x,-Math.sin((18+i*75)/180*Math.PI)*R+y); context.lineTo(Math.cos((54+i*75)/180*Math.PI)*r+x,-Math.sin((54+i*75)/180*Math.PI)*r+y); } context.closePath(); context.stroke(); context.fill(); } function drawsan(context,r,x,y){ // 画三角形 context.beginPath(); context.moveTo(x,y-r); context.lineTo(Math.cos( 320/180*Math.PI )*r+x,Math.sin(40/180*Math.PI )*r+y); context.lineTo(Math.cos( 210/180*Math.PI )*r+x,Math.sin(40/180*Math.PI )*r+y); context.closePath(); context.stroke(); context.fill(); } function draw(e) { g++; var mycanvas=document.getElementById('mycanvas'); var context=mycanvas.getContext('2d'); context.clearRect(0,0,mycanvas.width,mycanvas.height); context.strokeStyle="powderblue"; context.fillStyle="powderblue"; if(g%2==0){ drawsan(context, 30, getCanvasPos(mycanvas,e).x, getCanvasPos(mycanvas,e).y); } else{ drawStar(context,25,50,getCanvasPos(mycanvas,e).x,getCanvasPos(mycanvas,e).y); } } </script> </head> <body> <div onmousedown="draw(event)"> <canvas width="600px" height="400px" style="border: 1px solid black;" id="mycanvas"></canvas> </div> </body> </html>