精灵坐标查看器代码

一:写精灵查看器的总思路:

1监听鼠标事件我这里用onclick,当点击鼠标时,触发函数windowTocanvas(),drawBackground(),drawSpritesheet(),drawGuidelines()

2windowToCanvas()

实现相对于window窗口坐标到相对于canvas坐标的转化,要传进的canvas,window的x,y坐标参数

3drawSpritesheet();

新建一个精灵表图片对象

4drawGuidelines()

绘制坐标轴

5drawBackground()

绘制坐标轴后重新触发监听事件要擦拭掉之前定位画出的坐标轴,使用context,clearRect(startX,startY,width,height)擦拭该矩形区域的痕迹


html:


<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>精灵表</title>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
        }
        #mycanvas{
            background-color: burlywood;
        }
        #canvasbox{
            text-align: center;
        }
    </style>
</head>
<body>
<div id="readout"></div>
<div id="canvasbox">
    <canvas id="mycanvas" width="600" height="300">
        canvas is not support in your brower
    </canvas>
</div>
<script src="精灵跑步.js"></script>
</body>
</html>



js如下:

/**
 * Created by Administrator on 2015/4/27.
 */
var canvas = document.getElementById('mycanvas');
context = canvas.getContext('2d');
spritesheet = new Image();

canvas.onclick = function(e){
    var loc = windowTocanvas(canvas, e.clientX, e.clientY);
    console.log(loc.x,loc.y);//这里通过console打印出点击的点的canvas坐标
    drawBackground();
    drawSpritesheet();
    drawGuidelines(loc.x,loc.y);
};
function drawBackground(){
    context.clearRect(0,0,canvas.width,canvas.height);
}
function drawSpritesheet(){
    //context.drawImage()在画布上绘制图像,http://www.w3school.com.cn/tags/canvas_drawimage.asp
    context.drawImage(spritesheet,0,0);
}
function drawGuidelines(x,y){
    context.strokeStyle = 'rgba(0,0,230,0.8)';
    context.lineWidth = 0.5;//坐标轴的粗度为0.5
    //绘制纵坐标
    drawVerticalLine(x);
    //绘制横坐标
    drawHorizontalLine(y);
}
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();
}
function windowTocanvas(canvas,x,y){
    //获取canvas边框getBoundClientRect
    var bbox = canvas.getBoundingClientRect();
    //实现window窗口坐标到canvas画布坐标的转换
    return{x:(x-bbox.left)*(canvas.width /bbox.width),y:(y-bbox.top)*(canvas.height /bbox.height)};
}
//
spritesheet.src='1.png';

spritesheet.onload = function(e){
    drawSpritesheet();
};
drawBackground();



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值