将canvas中左上角的原点坐标位置改为左下角

  在使用canvas的时候,原点坐标在左上角,这个很烦人,因为一般的坐标基本都是在左下角,即笛卡尔坐标系,那怎么进行转变呢,在这里用到了canvas的translate,rotate,和scale进行转换,话不多说,上代码

 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<!DOCTYPE html>
<html lang="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>
    <title>笛卡尔坐标系</title>
</head>
 
<body onload="draw()">
<canvas id="myCanvus" width="440px" height="240px" style="border:1px dashed black;">
    出现文字表示你的浏览器不支持HTML5
</canvas>
</body>
</html>
<script type="text/javascript">
    <!--
    function draw(){
        var canvas=document.getElementById("myCanvus");
        var canvasWidth=440;
        var canvasHeight=240;
 
        var context=canvas.getContext("2d");
 
        context.fillStyle = "white";
        context.fillRect(0, 0, canvasWidth, canvasHeight);
 
        context.strokeStyle = "black";
        context.fillStyle = "black";
 
        context.save();
 
        // 进行坐标变换:把原点放在左下角,东方为X轴正向,北方为Y轴正向
 
        context.save();
        context.translate(0,canvasHeight);
        context.rotate(getRad(180));
        context.scale(-1,1);
 
 
        // 画折线
        context.beginPath();
        context.moveTo(0, 0);
        context.lineTo(50, 50);
        context.stroke();
        context.closePath();
 
        context.restore();
 
    }
 
    function getRad(degree){
        return degree/180*Math.PI;
    }
    //-->
</script>

  

posted @ 2021-09-15 15:30  勇敢牛牛20  阅读(661)  评论(0)    收藏  举报