今天逛博客,看到了这篇博文——【自己给自己题目做】之一:椭圆可点击区域。
博主用的dom方法实现的椭圆可点击区域,正好最近看angularJS看得晕坨坨的,
于是就想着转移一下注意力,做一下这个题目,本文用的canvas的方法实现
看一下demo
代码:
<!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width"> <link rel="stylesheet" type="text/css" href="http://css.cdn.tl/normalize.css"> <style type="text/css"> .wrapper{ width: 1000px; margin-left: auto; margin-right: auto; text-align: center; } canvas{ background-color: black; margin-top: 100px; } </style> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> </head> <body> <div class="wrapper"> <canvas id="canvas" width="800" height="600"></canvas> </div> <script> var demo = (function() { var canvas = document.getElementById('canvas'), context2D = canvas.getContext('2d'), ovalW = 200, //椭圆的水平半径 ovalH = 160, //椭圆的垂直半径 ovalX = 400, //椭圆原点x坐标 ovalY = 300; //椭圆原点y坐标 CanvasRenderingContext2D.prototype.oval = function (x, y, width, height) { var k = (width / 0.75) / 2, w = width / 2, h = height / 2; this.beginPath(); this.moveTo(x, y - h); this.bezierCurveTo(x + k, y - h, x + k, y + h, x, y + h); this.bezierCurveTo(x - k, y + h, x - k, y - h, x, y - h); this.closePath(); return this; } function drawOval() { context2D.oval(ovalX, ovalY, ovalW, ovalH); context2D.strokeStyle = 'rgb(255, 255, 255)'; context2D.stroke(); } function checkClick(event) { var event = event || window.event, mouseX = event.clientX, mouseY = event.clientY, canvasOffsetleft = canvas.offsetLeft, canvasOffsettop = canvas.offsetTop, scrollT = document.body.scrollTop, scrollL = document.body.scrollLeft; var x = mouseX + scrollL - canvasOffsetleft, y = mouseY + scrollT - canvasOffsettop; if((((x - ovalX) * (x - ovalX)) / ((ovalW / 2) * (ovalW / 2)) + ((y - ovalY) * (y - ovalY)) / ((ovalH / 2) * (ovalH / 2))) < 1) { alert('click'); } } return { init: function() { drawOval(); document.onclick = function(event) { checkClick(event); } } } })(); demo.init(); </script> </body> </html>
关于canvas画椭圆,发现无从下手,于是找了网上的资料,发现了这个http://jo2.org/html5-canvas-oval/
demo采用的是第四种方法:使用两条贝赛尔曲线画出椭圆,
就是这段代码:
CanvasRenderingContext2D.prototype.oval = function (x, y, width, height) { var k = (width / 0.75) / 2, w = width / 2, h = height / 2; this.beginPath(); this.moveTo(x, y - h); this.bezierCurveTo(x + k, y - h, x + k, y + h, x, y + h); this.bezierCurveTo(x - k, y + h, x - k, y - h, x, y - h); this.closePath(); return this; }
数学太神奇了,没能看懂。。。
而其他的大致就是判断鼠标点击位置(mouseX,mouseY)是否在椭圆中····