美文网首页
canvas里的文本基本操作

canvas里的文本基本操作

作者: infi_ | 来源:发表于2018-03-27 17:06 被阅读0次

    基本效果如图


    唯一需要注意的是 context.save()和context.restore()的应用
    这里为了不影响背景图 所以用save和restore

    var canvas=document.getElementById("canvas")
    var context=canvas.getContext("2d")
    var fillCheckbox   = document.getElementById('fillCheckbox')
    var strokeCheckbox = document.getElementById('strokeCheckbox')
    var shadowCheckbox = document.getElementById('shadowCheckbox')
    var text="HTML5";
    
    function draw(){
       context.clearRect(0,0,canvas.width,canvas.height)
    
       drawBackground()
    
       if(shadowCheckbox.checked){
           context.save()
        turnShadowsOn()
        drawText()
        context.restore()
       }else{
        context.save()
        turnShadowsOff()
        drawText()
        context.restore()
       }
       
    }
    
    function drawBackground(){
       var step_y=12
       var i=step_y*4
      
       while(i<context.canvas.height){
    
          context.beginPath()
          context.moveTo(0,i)
          context.lineTo(context.canvas.width,i)
          context.strokeStyle="gray"
          context.lineWidth="2"
    
          context.stroke()
          i+=step_y
    
        }
    
    
    }
    
    
    
    function turnShadowsOn(){
       context.shadowColor="rgba(0,0,0,0.8)"
       context.shadowOffsetX=5
       context.shadowOffsetY=5
       context.shadowBlur=10
    
    }
    function turnShadowsOff(){
      context.shadowColor=undefined;
      context.shadowOffsetX=0
      context.shadowOffsetY=0
      context.shadowBlur=0
    
    
    }
    
    function drawText(){
       var TEXT_X=65
       var TEXT_Y=canvas.height/2+35
    
       context.strokeStyle="blue"
    
       if(fillCheckbox.checked){context.fillText(text,TEXT_X,TEXT_Y)}
       if(strokeCheckbox.checked){context.strokeText(text,TEXT_X,TEXT_Y)}
    
    
    }
    context.font='128px Palatino'
    context.lineWidth=1.0
    context.fillStyle="cornflowerblue"
    
    fillCheckbox.onchange=draw
    strokeCheckbox.onchange=draw
    shadowCheckbox.onchange=draw
    
    draw()
    

    相关文章

      网友评论

          本文标题:canvas里的文本基本操作

          本文链接:https://www.haomeiwen.com/subject/usyscftx.html