简体   繁体   English

HTML画布大小调整和坐标空间

[英]Html Canvas Resizing And Coordinate Space

Note: I'm using Google Chrome 注意:我使用的是Google Chrome浏览器

Currently I have this test page 目前我有此测试页

http://www.evecakes.com/doodles/canvas_size_issue.htm http://www.evecakes.com/doodles/canvas_size_issue.htm

It should draw a rectangle right below the mouse cursor, but there are some really weird scaling issues which is causing it to draw at a varying offset. 应该在鼠标光标的下方绘制一个矩形,但是确实存在一些怪异的缩放问题,导致它以可变的偏移进行绘制。 I think it's because the canvas coordinate space is not increasing along with its html size. 我认为这是因为画布坐标空间没有随其html大小而增加。 Is there a way to increase that coordinate space size? 有没有办法增加该坐标空间的大小?

Here's the javascript function 这是javascript函数

$('#mapc').mousemove(function (event) {

            var canvas = $('#mapc');
            var ctx = canvas[0].getContext('2d');

            ctx.fillStyle = "rgb(200,0,0)";
            ctx.fillRect(event.clientX, event.clientY, 55, 50);

            document.title = event.clientX + " --- " + event.clientY;

        });

Set the width and height HTML attributes of the canvas. 设置画布的widthheight HTML属性。 Right now, it's assuming its default width and the CSS is just stretching it, and it appears as if it is scaling. 现在,它假定其默认宽度,而CSS只是在拉伸它,并且看起来好像在缩放。

A side-note, you can use this in the mousemove event - it is a reference to #mapc element, so you won't have to query the DOM on every mouse move. 附带一提,你可以使用thismousemove事件-这是一个参考#mapc的元素,所以你不会有查询的每个鼠标移动的DOM。

var offset = $('#mapc').offset();

$('#mapc').mousemove(function (event) {

    var ctx = this.getContext('2d');

    ctx.fillStyle = "rgb(200,0,0)";
    ctx.fillRect(event.pageX - offset.left, event.pageY - offset.top, 1, 1);
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM