如何使用按钮来调用在画布中绘制的函数

时间:2016-05-01 01:39:51

标签: javascript html5 function canvas

对于这个项目,我们正在使用canvas。我需要创建一些按钮,当您单击按钮时,应调用相应的功能。然后这些函数将在画布中绘制一些东西。但是,我的代码无效。按钮和画布本身会出现,但单击按钮时不会绘制任何内容。有什么错误吗?

<script>
    function drawCircle(){
        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d");
        ctx.beginPath();
        ctx.arc(95,50,40,0,2*Math.PI);
        ctx.stroke();
    }
    function drawLine(){
        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d");
        ctx.moveTo(0,0);
        ctx.lineTo(200,100);
        ctx.stroke();
    }
    function drawRectangle(){
        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d");
        ctx.fillStyle = "#FF0000";
        ctx.fillRect(0,0,150,75);
    }       
    function drawImage(){
        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d");
        var img = document.getElementById("scream");
        ctx.drawImage(img,10,10);
    }   
    function drawText(){
        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d");
        ctx.font = "30px Arial";
        ctx.fillText("Hello World",10,50);
    }

</script>
</head>


<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>

<input type="button" onclick="drawCircle();" value="Draw Circle">
<input type="button" onclick="drawLine();" value="Draw Line">
<input type="button" onclick="drawRectangle();" value="Draw Rectangle">
<input type="button" onclick="drawImage();" value="Draw Line">
<input type="button" onclick="drawText();" value="Text">
<input type="button" onclick="drawGradient();" value="Gradient">
<input type="button" onclick="scale();" value="Scale">
</body>
</html>

1 个答案:

答案 0 :(得分:0)

我在CodePen中尝试了您的代码,并且您已实现该功能的按钮工作正常。您的控制台是否显示任何错误?