精灵表坐标查看器-canvas学习第三天

这篇博客展示了如何利用JavaScript和HTML的canvas元素创建一个精灵表坐标查看器。通过JavaScript代码控制,配合HTML结构,实现了图片的展示和操作功能。

先来看效果图在这里插入图片描述
JavaScript的代码

var canvas = document.getElementById('canvas'),
	readout = document.getElementById('readout'),
	context = canvas.getContext('2d'),
	spritesheet = new Image();
 
 
//Functions
//将鼠标坐标转换成canvas坐标
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 VERTICAL_LINE_SPACING = 12;
		i = context.canvas.height;
	//清屏
	context.clearRect(0,0,canvas.width,canvas.height);
	context.strokeStyle = 'lightgray';
	context.lineWidth = 0.5;
 
	while(i > VERTICAL_LINE_SPACING*4){
		context.beginPath();
		//绘画从(0,i)绘制到(context.canvas.width,i)这条直线通过moveTo和lineTo函数进行绘画的
		context.moveTo(0,i);
		context.lineTo(context.canvas.width,i);
		context.stroke();
		i -=VERTICAL_LINE_SPACING;
 
	}
}
 
//绘画精灵表
function drawSpritesheet(){
	//drawImage(图片,x,y)
	context.drawImage(spritesheet,0,0);
}
 
function drawGuidelines(x,y){
	context.strokeStyle = 'rgba(0,0,230,0.8)';
	context.lineWidth = 0.5;
	drawVerticalLine(x);
	drawHorizontalLine(y);
}
 
//坐标的显示
function updateReadout(x,y) {
	//toFixed() 方法可把 Number 四舍五入为指定小数位数的数字。
	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();
}
//鼠标移动的位置
canvas.onmousemove = function (e) {
	var loc = windowToCanvas(canvas,e.clientX,e.clientY);
 
	drawBackground();
	drawSpritesheet();
	drawGuidelines(loc.x,loc.y);
	updateReadout(loc.x,loc.y);
}
//导入图片
spritesheet.src = 'a.png';
spritesheet.onload = function(e){
	drawSpritesheet();
}
//绘画
drawBackground();

HTML的代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sprite sheets</title>
<style>
	body{
		background: #dddddd;
	}
	
	#canvas{
		position:absolute;
		left: 0px;
		top: 20px;
		margin: 20px;
		background: #ffffff;
		border: thin inset rgba(100,150,230,0.5);
		cursor: pointer;
	}
	
	#readout{
		margin-top: 10px;
		margin-left: 15px;
		color: blue;
	}
</style>
</head>
<body>
	<div id='readout'></div>
	
	<canvas id='canvas' width='500' height='250'>
		Canvas not supported
	</canvas>
	<script src='js/sprites.js'></script>
</body>
</html>

图片随意找一张即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值