H5+js实现点击画板添加圆圈以及重点标注
<html> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" type="text/css" href="cho1.css"> <script src="jquery.js"></script> <script src="cho1.js"></script> </head> <body> <!-- onclick是绑定事件 (告诉浏览器在鼠标点击的时候要做什么) click是触发事件 (模拟了鼠标点击操作) --> <canvas width="500px" height="500px" id="draw" onclick="canvasClick"></canvas> <button class="create" onclick="addRandomCircle()">create</button> <button class="clear" onclick="clearCircles()">clear</button> </body> </html>
canvas{ border: 1px solid black; }
function Circle(x, y, radius, color) { this.x = x; this.y = y; this.radius = radius; this.color = color; this.isSelected = false; } var circles = []; var canvas; var context; window.onload = function () { canvas = document.getElementById("draw"); context = canvas.getContext("2d"); canvas.onmousedown = canvasClick; }; //添加圆圈 function addRandomCircle() { var radius = randomFromTo(10, 60); var x = randomFromTo(0, canvas.width); var y = randomFromTo(0, canvas.height); var colors = ['green', 'red', 'yellow', 'blue', 'black', 'orange', 'gray']; var color = colors[randomFromTo(0, 6)]; var circle = new Circle(x, y, radius, color); circles.push(circle); drawCircles(); } //实现随机数 function randomFromTo(min, max) { parseInt(Math.random() * (max - min + 1) + min, 10); return Math.floor(Math.random() * (max - min + 1) + min); } //清除圆圈 function clearCircles() { circles = []; drawCircles(); } //画圈圈 function drawCircles() { context.clearRect(0, 0, canvas.width, canvas.height); for (var i = 0; i < circles.length; i++) { var circle = circles[i]; context.beginPath(); context.globalAlpha = 0.85; context.arc(circle.x, circle.y, circle.radius, 0, Math.PI * 2); context.fillStyle = circle.color; context.strokeStyle = "black"; if (circle.isSelected) { context.lineWidth = 5; } else { context.lineWidth = 1; } context.fill(); context.stroke(); } } var previousSelectedCircle; //点击事件 function canvasClick(e) { var clickX = e.pageX - canvas.offsetLeft; var clickY = e.pageY - canvas.offsetTop; for (var i = circles.length - 1; i >= 0; i--) { var circle = circles[i]; var distanceFromCenter = Math.sqrt( Math.pow(circle.x - clickX, 2) + Math.pow(circle.y - clickY, 2)); if (distanceFromCenter <= circle.radius) { if (previousSelectedCircle != null) { previousSelectedCircle.isSelected = false; } previousSelectedCircle = circle; circle.isSelected = true; drawCircles(); return; } } }
注意对于click和onclick等的区别
浙公网安备 33010602011771号