在画布中绘制箭头时出错

时间:2015-02-23 17:24:59

标签: javascript jquery canvas

我编写代码但它没有运行。 我有2个标签画布。当我改变画布的属性高度< 100然后箭头隐藏。如果我没有在标签画布之前写标签div它运行正常。谢谢你的支持!!!! 源代码:

<body>
<div id="yendau">LOL</div>
<canvas id="c" width="500" height="100">Brower of you doesn't not support Canvas</canvas>
<div>Yolooooooooooo</div>
<canvas id="d" width="500" height="300">Brower of you doesn't not support Canvas</canvas>


<script src="jquery-1.9.1.js"></script>
<script langauage="javascript">



function canvas_arrow(context, fromx, fromy, tox, toy){
    var headlen = 20;   // length of head in pixels
    var dx = tox-fromx;
    var dy = toy-fromy;
    var angle = Math.atan2(dy,dx);
    context.moveTo(fromx, fromy);
    context.lineTo(tox, toy);
    context.lineWidth=2;

    context.moveTo(tox, toy);
    context.lineTo(tox-headlen*Math.cos(angle+Math.PI/6),toy-headlen*Math.sin(angle+Math.PI/6));
    context.moveTo(tox, toy);
    context.lineTo(tox-headlen*Math.cos(angle-Math.PI/6),toy-headlen*Math.sin(angle-Math.PI/6));
}

$('document').ready(function(){
    var count= parseInt($("canvas").length);
    for(var i=0; i< count; i++){
        var ctx= $("canvas")[i].getContext('2d');
        ctx.beginPath();
        //var x= $('#c').offset().left-15;
        //var y= $('#c').offset().top-15;
        var x= $('#'+$("canvas")[i].id).offset().left;
        var y= $('#'+$("canvas")[i].id).offset().top+15;
        var x1= x+100;
        canvas_arrow(ctx,x,y,x1,y);
        ctx.stroke();
    }
});

1 个答案:

答案 0 :(得分:0)

在计算x,y时,您不需要添加画布的偏移量。在你的情况下,这样做会很快将你的箭头从画布上移开。

在计算鼠标位置时,画布偏移很有用,但在画布本身上绘制时无效。这是因为鼠标坐标始终相对于页面的左上角 - 而不是画布的左上角。

画布的左上角是x = 0,y = 0。因此,只需将x,y设置为所需的坐标:

    当您向右移动画布时,
  • x从零开始增加。

  • 当你向下移动画布时,
  • y从零增加。