HTML5 Canvas实现图片缩放、翻转、颜色渐变的代码示例

2020-04-21 23:05:06易采站长站整理

    context.strokeStyle = ‘#000000’;   
    context.strokeRect(200,50,100,50);   
    // 默认旋转是根据0,0中心,使用translate可以按照自己的设置的中心旋转   
    context.translate(250,75);   
       
    context.rotate(45 * Math.PI /180);   
    context.translate(-250, -75);   
  
    context.beginPath();   
    context.strokeStyle = ‘#cccccc’;   
    context.strokeRect(200,50,100,50);   
        
    // transform 矩阵   
    context.beginPath();   
    context.strokeStyle = ‘#000000’;   
    context.strokeRect(10,10,150,100);   
       
    context.transform(3,0,0,3,0,0);   
    context.beginPath();   
    context.strokeStyle = ‘#cccccc’;   
    context.strokeRect(10,10,150,100);   
        
}  

渐变、图像组合效果、颜色翻转

XML/HTML Code复制内容到剪贴板

var canvas = document.getElementById(‘canvas’);   
if (canvas.getContext) {   
    var context = canvas.getContext(‘2d’);   
    // 线性绘制渐变   
    var grd = context.createLinearGradient(0,0,200,100);   
    // postion 必须是0.1-1.0之间的竖直,表示渐变中颜色的地点相对地位,color表示颜色   
    grd.addColorStop(0.1, "#00ff00");   
    grd.addColorStop(0.8, "#ff0000");   
       
    context.fillStyle = grd;   
    context.fillRect(0,0, 200,100);   
    // 径向渐变   
    var grd = context.createRadialGradient(100,100,10,100,100,50);   
    grd.addColorStop(0.1, "#00ff00");   
    grd.addColorStop(0.8, ‘#ff0000’);