1. 程式人生 > >用python和html5在畫布上畫個車子和笑臉

用python和html5在畫布上畫個車子和笑臉

 畫汽車

python提供了tutle(海龜)模組。這個模組提供了編寫向量圖的方法,基本上就是畫直線,點和曲線。

海龜是怎樣工作的,首先讓python匯入turtle模組。

import turtle

引入turtle模組後,呼叫turle模組中的Pen函式,它會自動建立一塊畫布,並且帶一個箭頭(它就代表海龜)。

t=turtle.Pen()

我們使用剛建立的t的函式給海龜發指令。

forward指令讓海龜向前50個畫素,t.forward(50)。

 t.left(90)

t.right(90)

海龜左右旋轉。

t.reset()

清除畫布並且把海龜放在開始位置。

t.clear()

清除螢幕,海龜仍然在原位。

t.up()

畫筆放下來不在作畫

t.down()

畫筆擡起來重新開始畫畫

畫汽車程式碼:

import turtle
t = turtle.Pen()
t.reset()
t.color(1, 0, 0)
t.begin_fill()
t.forward(100)
t.left(90)
t.forward(20)
t.left(90)
t.forward(20)
t.right(90)
t.forward(20)
t.left(90)
t.forward(60)
t.left(90)
t.forward(20)
t.right(90)
t.forward(20)
t.left(90)
t.forward(20)
t.end_fill()

#第一個輪胎
t.color(0, 0, 0)
t.up()
t.forward(10)
t.down()
t.begin_fill()
t.circle(10)
t.end_fill()

#第二個輪胎
t.setheading(0)
t.up()
t.forward(90)
t.right(90)
t.forward(10)
t.setheading(0)
t.begin_fill()
t.down()
t.circle(10)
t.end_fill()
效果圖如下: 裡面用到的函式:

t.color()

改變畫筆的顏色

begin_fill和end_fill用來給畫布上一個區域填色的

circle繪畫一個指定大小的圓

setheading讓海龜面向指定的方向

好啦汽車到此就畫完了。

畫笑臉

canvas為html5最顯著,使用得最廣泛的元素

整個繪畫庫都基於上色的div元素。

程式碼如下:

<canvas id ="mycanvas"></canvas>
<script>
    var canvas = document.getElementById("mycanvas"),
    ctx=canvas.getContext("2d");
    canvas.width=canvas.height=200;
    //畫兩個藍色的圓
    ctx.fillStyle="blue";
    ctx.beginPath();
    ctx.arc(50,50,25,0,Math.PI*2,true);
    ctx.arc(150,50,25,0,Math.PI*2,true);
    ctx.fill();
    //畫一個紅色三角形
    ctx.fillStyle="red";
    ctx.beginPath();
    ctx.moveTo(100,75);
    ctx.lineTo(75,125);
    ctx.lineTo(125,125);
    ctx.fill();
    //畫一個綠色的半圓
    ctx.strokeStyle="green";
    ctx.beginPath();
    ctx.scale(1,0.5);
    ctx.arc(100,300,75,Math.PI,0,true);
    ctx.closePath();
    ctx.stroke();
</script>
效果圖如下:

(canvas程式碼沒有太多註釋,有時間會補上,吐舌頭)