【问题标题】:HTML5 canvas path drawing issueHTML5画布路径绘制问题
【发布时间】:2013-01-13 21:23:04
【问题描述】:

我在尝试用画布画线时发现了一个奇怪的问题。我有一个简单的脚本,当你第一次点击时保存点(这将是路径的起点),当你再次点击并且第一个点已经保存时,它会保存终点。所以我有路径的起点和终点,这没关系。在此之后,我使用 .moveTo()、.lineTo() 和 .stroke() 函数来绘制一条线。这里出现了问题:X 坐标总是比原始坐标(起点和终点)多 1.4 倍,Y 坐标少​​ 0.8 倍。我不知道是什么导致了这个问题。我正在跟踪变量,它们工作正常,.moveTo() 和 .lineTo() 函数获得正确的坐标,但它们绘制了转换后的线。

这是我的代码:

var points = [null, null];
var canvas = $('canvas#myid');
var ctx = canvas[0].getContext("2d");
var end = false;

$(canvas).click(function(event) {
   if ( null == points[0] ) { 
      // First click - first coordinates
      points[0] = [event.pageX, event.pageY];
   } else if ( null == points[1] && null != points[0] ) {
      // Second click - second coordinates
      points[1] = [event.pageX, event.pageY];
      ctx.fillStyle = "black";
      ctx.moveTo(points[0][0], points[0][1]);
      ctx.lineTo(points[1][0], points[1][1]);
      ctx.stroke();
      end = true;
   } else if ( null != points[0] && null != points[1] ) end = true;

   if ( true === end ) {
      points = [null, null];
   }
}

我不知道,希望你们能帮助我,谢谢!

【问题讨论】:

  • 你能在JSFiddle.com上添加一个演示吗?
  • @AmaanCheval 你的意思是jsfiddle.net?
  • 我已经做了一个演示,但效果很好。也许这是一些 CSS 问题,请稍等..
  • 代码似乎正确fiddle。只有当画布不在页面的左上角时,pageX/Y 才合适。
  • @TwiNight 画布在页面左上角,为什么不起作用?

标签: html canvas path line draw


【解决方案1】:

您忘记在代码末尾关闭括号 ); 并且不需要使用 $(canvas). 您应该像 canvas. 一样使用它

jsFiddle Live Demo

$(function()
{
    var points = [null, null];
    var canvas = $('canvas#myid');
    var ctx = canvas[0].getContext("2d");
    var end = false;
    canvas.click(function(event) 
    {
           if ( null == points[0] ) 
           { 
                  // First click - first coordinates
                  points[0] = [event.pageX, event.pageY];
           } 
           else if ( null == points[1] && null != points[0] ) 
           {
                  // Second click - second coordinates
                  points[1] = [event.pageX, event.pageY];
                  ctx.fillStyle = "black";
                  ctx.moveTo(points[0][0], points[0][1]);
                  ctx.lineTo(points[1][0], points[1][1]);
                  ctx.stroke();
                  end = true;
           } 
           else if ( null != points[0] && null != points[1] ) 
           {
                 end = true;
           }
           if ( true === end ) 
           {
                points = [null, null];
           }
    }); // Here you missed
});

【讨论】:

  • HTML 中出现错误。我的画布上有一个 width="1024" 和 height="600" 属性。加载页面时,我将画布样式的宽度和高度更改为窗口的大小 - 这就是问题所在。画布默认为 1024*600,但我缩放到其他大小,这会导致转换。当我更改画布的宽度和高度属性而不是样式宽度和高度时,它可以正常工作并且没有任何转换。
  • @VargaTamas 这样您就可以再次获得新的高度和宽度,例如:var width = canvas.width();
猜你喜欢
  • 2019-04-12
  • 2014-10-16
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-18
相关资源
最近更新 更多