您的位置:首页 > Web前端 > HTML5

7.HTML5 高级Canvas技术-2

2013-12-31 04:35 260 查看
<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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: