//HTML代码
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Sprite sheets</title>
<link href="style/canvas.min.css" rel="stylesheet" />
</head>
<body>
<div id="readout"></div>
<canvas id="canvas" width="500" height="250">
canvas not supported
</canvas>
<script src="javascript/canvas.min.js"></script>
</body>
</html>
//CSS样式
body {
background:#dddddd;
}
#canvas {
position:absolute;
left:0px;
top:40px;
margin:0px;
background:#ffffff;
border:thin inset rgba(100,150,230,0.5);
cursor:pointer;
}
#readout {
margin-top:10px;
margin-left:15px;
color:blue;
}
//JAVASCRIPT代码
var canvas = document.getElementById('canvas'),
readout = document.getElementById('readout'),
context = canvas.getContext('2d'),
spritesheet = new Image();
//functions.......................................
function windowToCanvas(canvas, x, y) {
var bbox = canvas.getBoundingClientRect();
return {
x: x - bbox.left * (canvas.width / bbox.width),
y: y - bbox.top * (canvas.height / bbox.height)
};
}
function drawBackground() {
var vertcal_line_spacing = 12,
i = context.canvas.height;
context.clearRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = 'lightgray';
context.lineWidth = 0.5;
while (i> vertcal_line_spacing*4) {
context.beginPath();
context.moveTo(0, i);
context.lineTo(context.canvas.width, i);
context.stroke();
i -= vertcal_line_spacing;
}
}
function drawSpritesheet() {
context.drawImage(spritesheet,0,0);
}
function drawGuidelines(x, y) {
context.strokeStyle = 'rgba(0,0,230,0,0.8)';
context.lineWidth = 0.5;
drawVerticalLine(x);
drawHorizontalLine(y);
}
function updateReadout(x, y) {
readout.innerText = '('+x.toFixed(0)+','+y.toFixed(0)+')';
}
function drawHorizontalLine(y) {
context.beginPath();
context.moveTo(0, y + 0.5);
context.lineTo(context.canvas.width, y + 0.5);
context.stroke();
}
function drawVerticalLine(x) {
context.beginPath();
context.moveTo(x + 0.5, 0);
context.lineTo(x + 0.5, context.canvas.height);
context.stroke();
}
//Event handlers.........................................
canvas.onmousemove = function (e) {
var loc = windowToCanvas(canvas, e.clientX, e.clientY);
drawBackground();
drawSpritesheet();
drawGuidelines(loc.x, loc.y);
updateReadout(loc.x, loc.y);
}
//Initialization.........................................
spritesheet.src = 'sprite.jpg';
spritesheet.onload = function (e) {
drawSpritesheet();
}
drawBackground();