将位置坐标转换为画布坐标 [英] Convert position coordinates to canvas coordinates

查看:333
本文介绍了将位置坐标转换为画布坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将游戏中的位置坐标转换为HTML5 Canvas坐标.

I have to convert ingame position coordinates to HTML5 Canvas coordinates.

给定的坐标类似于

-2159.968750,-926.968750
-2159.968750,-704.031250
-2026.847167,-926.993835

给定的坐标不代表画布坐标之类的像素.

The given coordinates do not represent pixels like Canvas coordinates.

是否有任何方法可以将仅具有几个校准坐标的任何给定坐标转换为相应的画布坐标?

Is there any method to convert any given coordinate to the corresponding canvas coordinate with only a few calibration coordinates?

例如,我知道画布上的坐标#1是(66,980),画布上的坐标#2是(66,933).

For example i know that coordinate #1 is (66, 980) on the canvas and coordinate #2 is (66, 933) on the canvas.

预先感谢

推荐答案

您最可能想要的是在画布上显示游戏虚拟世界的一部分.

What you most probably want is to show a part of the virtual world of your game on the canvas.

•首先要做的是确定该视图的正确性并以某种方式存储它.
最简单的:

• First thing is you have to decide of this view rect and store it in some way.
Most simple :

var viewRect = { x : -3000, y:-3000, width: 6000, height:6000 } ;

•然后,当您要绘制时,我建议您让画布为您做数学运算并使用变换.

• Then, when you want to draw, i suggest you let the canvas do the math for you and use a transform.

因此,根据您的猜测初始化了'canvasWidth'和'canvasHeight',绘制代码如下:

So with ‘canvasWidth‘ and ‘canvasHeight‘ initialized as you guess, the drawing code looks like :

context.clearRect(0,0,canvasWidth, canvasHeight);
context.save();
var ratio = canvasWidth / viewRect.width;
context.scale(ratio, ratio);
context.translate(-viewRect.x, -viewRect.y);
//
// do your drawings here in world coordinates.
context.fillStyle='black';
context.fillRect(-2000, -800, 300, 300);
//
context.restore();

请注意,您必须保存()和恢复()上下文,以使其在每个渲染器上均保持正确.

Notice that you have to save() and restore() the context to keep it correct on each render.

(您也可能不使用保存/恢复,而是使用"setTransform(1、0、0、1、0、0);"来重置转换.)

(You might also not use save/restore and use ‘setTransform(1, 0, 0, 1, 0, 0);‘ to reset the transform.)

最简单的jsbin在这里: http://jsbin.com/hudaqoqavu/1/

most simple jsbin is here : http://jsbin.com/hudaqoqavu/1/

这篇关于将位置坐标转换为画布坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆