简体   繁体   English

为什么jCanvas绘制错误的像素?

[英]Why jCanvas draws wrong pixels?

I have an object of pixel map, each row contains an object of columns, that contains a colour information. 我有一个像素图对象,每一行包含一个列对象,其中包含一个颜色信息。 Then I choose the colour using switch() , and then I simply draw it to canvas. 然后,使用switch()选择颜色,然后将其简单地绘制到画布上。 Here is the code: 这是代码:

  for(var pixX in pixmap) {
    for(var pixY in pixmap[pixX]) {
      switch(pixmap[pixX][pixY]) {
        case 1: var pixColor='lightgray'; break;
        case 2: var pixColor='black'; break;
        default: var pixColor='forestgreen'; break;
        }
      $('canvas#surface').drawRect({
        fillStyle: pixColor,
        width: 1, height: 1,
        x: pixX, y: pixY,
        fromCenter: false
        });
      }
    }

It draws the pixels, but the pixel position is somehow zoomed, although, the pixels are really just 1px big. 它绘制像素,但是像素位置以某种方式缩放,尽管像素实际上只有1px大。 I can't determine, how much it zooms. 我无法确定它放大了多少。 When I draw after a while to the canvas, the position is correct. 过一会儿我在画布上绘画时,位置是正确的。 What's the problem? 有什么问题?

Edit: I've recreated it on jsFiddle: http://jsfiddle.net/qyNTn/ 编辑:我已经在jsFiddle上重新创建它: http : //jsfiddle.net/qyNTn/

Simply put, the pixX and pixY variables are converted to strings by JavaScript. 简而言之, pixXpixY变量通过JavaScript转换为字符串。 You need to convert pixX and pixY to numbers before passing them to jCanvas. 您需要pixXpixY转换为数字,然后再将它们传递给jCanvas。

The reason being is because JavaScript stores each key name (for any object) as a string. 原因是因为JavaScript将每个键名称(对于任何对象)存储为字符串。 Therefore, when you iterate through an object using a for in loop, the key name will always be a string. 因此,当您使用for in循环遍历对象时,键名将始终是字符串。 In other words, pixX and pixY are treated as strings, so you need to convert them to numbers using a function such as parseFloat . 换句话说, pixXpixY被视为字符串,因此您需要使用诸如parseFloat的函数将它们转换为数字。

In addition, jCanvas performs many numerical calculations when drawing shapes, so it always prefers a number over a string for any numerical value. 此外,jCanvas在绘制形状时会执行许多数值计算,因此对于任何数值,它总是首选数字而不是字符串。

Anyway, fixing your code (to produce the expected behavior) only requires a single change to your drawRect() parameters. 无论如何,修复代码(以产生预期的行为)只需要对drawRect()参数进行一次更改。

x: parseFloat(pixX), y: parseFloat(pixY),

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

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