1. 程式人生 > >canvas方法

canvas方法

參考網站

一、w3School

二、canvas的基本用法

1、var canvas=document.getElementById('canvas')//找到canvas元素

2、var context=canvas.getContext('2d')//建立contetx物件

3、canvas多種內建方法

context.beginPath()

context.closePath()

(1)繪製一條直線

        context.moveTo(0,0)       //從(0,0)開始座標
        context.lineTo(100,100)  //(100,100)結束座標
        context.lineWidth='10'     //線條寬度
        context.strokeStyle='blue'//線條顏色
        context.stroke()                //開始繪製

(2) 畫圓

canvas(centerx,centery,radius,startingAngle,endingAngle,antclockwise=false)
canvas(x軸座標,y軸座標,角度,開始的角度,結束的角度,順時針(預設false)/逆時針true)

(3)填充顏色

context.fillStyle='red'
context.fill()

(3)建立矩形

context.react(x,y,width,height)//繪製矩形
ctx.fillRect(0,0,300,150);//繪製被填充的矩形
ctx.fillStyle="red";//被填充矩形的顏色
ctx.clearRect(20,20,100,50);//在給定的矩形內清除指定的畫素

(4)繪製五角星

   function drawStar(cxt,r,R,x,y,rot){
        cxt.beginPath()
        for(var i=0;i<5;i++){
            cxt.lineTo(Math.cos((18+i*72-rot)/180*Math.PI)*R+x,-Math.sin((18+i*72-rot)/180*Math.PI)*R+y)
            cxt.lineTo(Math.cos((54+i*72-rot)/180*Math.PI)*r+x,-Math.sin((54+i*72-rot)/180*Math.PI)*r+y)
        }
        cxt.closePath()
        cxt.stroke()
    }

(5)context.save()與context.restore()成對出現