1

我正在尝试制作一个程序,该程序从一些计算中收集到的信息并将其绘制在画布图上。但是,我需要缩放图表,以便它可以容纳更大的数字。但是每次我把ctx.scale();整个画布空白都拿出来!我想我可以通过先缩放画布来阻止这种情况,但是缩放后画布上什么也没有画。

这是我的画布的编码:

var c=document.getElementById("graph_");
        var ctx=c.getContext("2d");
        graph_.style.backgroundColor="white";
        var z0=Math.max(Math.abs(a),Math.abs(b));
        var z=Math.round(z0);           
        var z1=Math.round(z);
        var z2=z*2
        // alert(z1);   
        // alert(z2);

        ctx.scale(3200/z,3200/z)    

        var xnew=360/2+360/2*a
        var ynew=360/2-360/2*b
        alert(xnew);    
        alert(ynew);

        ctx.font = '10px Calibri';
        ctx.fillText("( 0 , 0 )", 125, 85);
        ctx.fillText(z1, 210, 87);
        ctx.fillText(z2, 270, 87);

        ctx.fillText(z1*-1, 75, 87);
        ctx.fillText(z2*-1, 0, 87);

        ctx.fillText(z1, 120, 43.5);
        ctx.fillText(z2, 120, 10);

        ctx.fillText(z1*-1, 120, 120);
        ctx.fillText(z2*-1, 120, 145);

        ctx.lineWidth = 1;
        ctx.beginPath()
        ctx.moveTo(150, 0);
        ctx.lineTo(150, 400);
        ctx.closePath();

        ctx.lineWidth = .2;
        ctx.moveTo(0, 75);
        ctx.lineTo(400, 75);
        ctx.strokeStyle = "#8B8682";
        ctx.stroke();
        ctx.closePath();

          ctx.beginPath();
          ctx.lineWidth = 2;
          ctx.moveTo(xnew, 180);
          ctx.lineTo(180, ynew);
          ctx.strokeStyle = "red";
          ctx.stroke();                         

4

2 回答 2

1

实际上,这些东西正在被绘制到画布上,你只是看不到它,因为你放大得太远并且仍然在图表的左上角,因为绘图的默认原点在左上角0,0。

因此,如果您想放大那么远(即使您可能想缩小以显示更大的数字,即图形上更大的图纸),您需要将画布原点转换为您的新原点(您的左上角)想看)在你缩放上下文之前。

您可以使用 translate 方法,例如

ctx.translate(newX,newY);

但在您这样做之前,您将要保存上下文的状态,以便您可以恢复到它。

假设您想放大图形的中心,您将转换为以下点:

ctx.translate((-c.width /2 * scale) + offsetX,(-c.height / 2 * scale) + offsetY);

where the offsetX is the canvas width / 2 and offsetY is the canvas height / 2 and the scale is by the amount that you're scaling in you ctx.scale call.

于 2012-06-07T17:42:56.950 回答
0

的值3200/z究竟是多少?

我猜你正在大量缩放画布,以至于屏幕上唯一可见的东西就是画布的前几个像素。由于您没有在屏幕左上角的 5 个像素中绘制任何内容,因此您什么也看不到。

于 2012-06-07T14:45:06.897 回答