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

2019-01-28 15:27:48丽君

翻转、移动、平移、放大、缩小

XML/HTML Code复制内容到剪贴板
  1. var canvas = document.getElementById('canvas');    if (canvas.getContext) {   
  2.     var context = canvas.getContext('2d');        // 放大与缩小   
  3.     context.beginPath();        context.strokeStyle = "#000000";   
  4.     context.strokeRect(10,10,150,100);            
  5.     // 放大3倍        context.scale(3,3);   
  6.     context.beginPath();        context.strokeStyle = '#cccccc';   
  7.     context.strokeRect(10,10,150,100)            
  8.     // 缩小        context.scale(0.5,0.5);   
  9.     context.beginPath();        context.strokeStyle = '#cccccc';   
  10.     context.strokeRect(10,10,150,100)            
  11.      // 翻转        var img = new Image();   
  12.     img.src = 'images/1.jpg';        img.onload = function(){   
  13.         context.drawImage(img, 10,10);                    context.scale(1, -1);   
  14.         context.drawImage(img, 0, -500);        }   
  15.     // 平移        context.beginPath();   
  16.     context.strokeStyle = '#000000';        context.strokeRect(10,101,150,100);   
  17.     // x移动 50  y 移动100        context.translate(50,100);   
  18.     context.beginPath();        context.strokeStyle = '#cccccc';   
  19.     context.strokeRect(10,10,150,100);        // 旋转   
  20.     context.beginPath();        context.strokeStyle = '#000000';   
  21.     context.strokeRect(200,50,100,50);        // 默认旋转是根据0,0中心,使用translate可以按照自己的设置的中心旋转   
  22.     context.translate(250,75);           
  23.     context.rotate(45 * Math.PI /180);        context.translate(-250, -75);   
  24.        context.beginPath();   
  25.     context.strokeStyle = '#cccccc';        context.strokeRect(200,50,100,50);   
  26.              // transform 矩阵   
  27.     context.beginPath();        context.strokeStyle = '#000000';   
  28.     context.strokeRect(10,10,150,100);           
  29.     context.transform(3,0,0,3,0,0);        context.beginPath();   
  30.     context.strokeStyle = '#cccccc';        context.strokeRect(10,10,150,100);   
  31.          }