canvas 繪圖

canvas

<canvas id="drawing" width="200" height="200">xxx</canvas>
<script>
    var drawing = document.getElementById('drawing')
    
    //傳入 2d 就可以獲得 2D 上下文
    drawing.getContent('2d')
    
    //保存圖片,添加到頁面中
    var imgURL = drawing.toDataURL('image/png')
    var img = document.createElement('img')
    img.src = imgURL
    document.body.appendChild(img)
    
    //矩形填充
    context.fillStyle = '#0000ff'
    context.fillRect(10,10,50,50)
    
    //矩形描邊
    context.strokeStyle = 'red';
    context.strokeRect(10,60,50,50)
    
    //清除矩形
    context.clearRect(20,20,10,10)
    
    //保存和調(diào)用上下文
    ctx.fillStyle='#ff0000'
    ctx.save()

    ctx.fillStyle='#00ff00'
    ctx.translate(100,100)
    ctx.save()

    ctx.fillStyle='#000000'
    ctx.translate(200,200)
    ctx.save()

    ctx.fillStyle='#0000ff'
    ctx.fillRect(0,0,100,200)

    ctx.restore()
    ctx.fillRect(10,10,100,200)

    ctx.restore()
    ctx.fillRect(0,0,100,200)

    ctx.restore()
    ctx.fillRect(20,20,100,200)
    
</script>

canvas必須先設(shè)置widthheight

  1. getContext("2d")傳入 2d 就可以獲得 2D 上下文
  2. toDataURL('image/png')可以把canvas畫的圖片保存下來,默認(rèn)格式為png,也可設(shè)置為jpeg
  3. fillRect(x,y,width,height)填充矩形,fillStyle填充顏色
  4. strokeRect(x,y,width,height)描邊矩形,strokeStyle描邊顏色
  5. lineWidth設(shè)置線條寬度
  6. lineCap設(shè)置線條末尾的形狀,取值:butt平頭,round圓頭,square方頭
  7. lineJoin設(shè)置線條相交方式,取值:round圓交,bevel斜交,miter斜接
  8. clearRect(x,y,width.height)清除矩形
  9. translate(x,y)變換原點坐標(biāo),將原點坐標(biāo)移動到(x,y)
  10. rotate()圍繞原點旋轉(zhuǎn)
  11. save()保存上下,只保存上下文的設(shè)置和變換,不會保存上下文的內(nèi)容
  12. restore()調(diào)用上下文,調(diào)用從最近一個save()開始調(diào)用,逐級往上。
  13. drawImage(繪制的圖像,源圖像x,源圖像y,源圖像width,源圖像height,目標(biāo)圖像x,目標(biāo)圖像y,目標(biāo)圖像width,目標(biāo)圖像height)
  14. globalAlpha設(shè)置全局透明度
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容