7.HTML5 高级Canvas技术-2

来源:互联网 发布:淘宝格子铺是真是假 编辑:程序博客网 时间:2024/05/21 20:26
<body><script>     var circles = [];var canvas;var context;var selectedCircle;window.onload = function() {  canvas = document.getElementById("drawingCanvas");  context = canvas.getContext("2d");  canvas.onmousedown = canvasClick;  canvas.onmouseup = stopDragging;  canvas.onmouseout = stopDragging;  canvas.onmousemove = dragCircle;};function Circle(x, y, radius, color) {  this.x = x;  this.y = y;  this.radius = radius;  this.color = color;  this.isSelected = false;}function addRandomCircle() {var radius = randomFromTo(10, 60);var x = randomFromTo(0, canvas.width);var y = randomFromTo(0, canvas.height);var colors = ["green", "blue", "red", "yellow", "magenta", "orange", "brown", "purple", "pink"];var color = colors[randomFromTo(0, 8)];  var circle = new Circle(x, y, radius, color);  circles.push(circle);drawCircles(circle);refreshCanvas();}function clearCanvas() {   circles = [];   refreshCanvas();}function refreshCanvas(){  context.clearRect(0, 0, canvas.width, canvas.height);  for(var i=0; i<circles.length; i++) {drawCircles(circles[i]);}}function drawCircles(circle) {      context.globalAlpha = 0.85;    context.beginPath();    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();}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 (selectedCircle != null) selectedCircle.isSelected = false;       selectedCircle = circle;      circle.isSelected = true;      isDragging = true;      refreshCanvas();      return;    }  }}var isDragging = false;function stopDragging() {  isDragging = false;}function dragCircle(e) {   if (isDragging == true) {     if (selectedCircle != null) {       var x = e.pageX - canvas.offsetLeft;      var y = e.pageY - canvas.offsetTop;       selectedCircle.x = x;      selectedCircle.y = y;       refreshCanvas();    }  }}function randomFromTo(from, to) {  return Math.floor(Math.random() * (to - from + 1) + from);}</script><canvas id="drawingCanvas" width="600px" height="600px"></canvas> <div>    <button onclick="addRandomCircle()">Add Circle</button>    <button onclick="clearCanvas()">Clear Canvas</button></div></body>

0 0
原创粉丝点击