<Canvas>
元素
<Canvas>
元素是HTML5引入的一个强大的绘图元素,它允许通过 JavaScript 在网页上动态绘制图形、动画和交互式内容。需要注意的是,<Canvas>
元素只是图形的一个容器,绘制图形必须使用Javascript。
空画布
<canvas id="huabu" width="200" height="200" style="border: 2px solid #000000;"></canvas>
画线
<script>var c = document.getElementById("huabu");var ctx = c.getContext("2d");// 画线ctx.beginPath();ctx.moveTo(0, 0);ctx.lineTo(200, 200);ctx.stroke();
</script>
画圆
<script>var c = document.getElementById("huabu");var ctx = c.getContext("2d");// 画圆ctx.beginPath();ctx.arc(95,50,40,0,2*Math.PI);ctx.stroke();
</script>
文本
<script>var c = document.getElementById("huabu");var ctx = c.getContext("2d");// 文本ctx.font = "30px Arial";ctx.fillText("Hello World",10,50);
</script>
空心文本
<script>var c = document.getElementById("huabu");var ctx = c.getContext("2d");// 空心文本ctx.font = "30px Arial";ctx.strokeText("Hello World",10,50);
</script>
画线性渐变
<script>var c = document.getElementById("huabu");var ctx = c.getContext("2d");// 画线性渐变var grd =ctx.createLinearGradient(0,0,200,0);grd.addColorStop(0,"red");grd.addColorStop(1,"white");ctx.fillStyle = grd;ctx.fillRect(10,10,150,80);
</script>
画圆渐变
<script>var c = document.getElementById("huabu");var ctx = c.getContext("2d");// 画圆渐变var grd =ctx.createLinearGradient(75,50,5,90,60,100);grd.addColorStop(0,"red");grd.addColorStop(1,"white");ctx.fillStyle = grd;ctx.fillRect(10,10,150,80);
</script>
画图片
<script>var c = document.getElementById("huabu");var ctx = c.getContext("2d");// 画图片var img = document.getElementById("scream");ctx.drawImage(img,10,10);</script>