技术开发 频道

如何用HTML5 Canvas为Web图形创建特效

  【IT168 技术】HTML5 Canvas 将使用像素在屏幕上绘制图形图像。 本节演示了五种用于操作像素以创建摄影特效的 Canvas 技术。 您可使用这些技术来生成独具特色的图像,为您的网站、博客、视频游戏画面、广告和插图等提供信息或艺术趣味。

  本教程包含五个独立的带有注释的代码示例,为您演示了这些技术如何改善一张有关美洲鹰的摄影图像。 这些示例解释了如何执行以下操作: 将美洲鹰的照片放置在一个圆形中;向背景中添加白雪纹理图片;大幅改变色彩构成;使图像变得透明;并将整张图片从彩色变为黑白。

  本主题介绍如何使用 HTML5 Canvas 将照片放入不同形状中,并为 Web 设计创建视觉特效。

  本主题包含一个独立的带有注释的代码示例,演示如何将一张有关美洲鹰的照片放入到一个圆形形状中。 此代码示例演示了如何使用 Canvas 加载美洲鹰照片并显示在屏幕上。 然后,它演示如何使用 Canvas arc 方法创建一个圆,并围绕美洲鹰添加一个白色圆形框。 此示例末尾的讨论材料将说明有关代码如何工作来开发此技术的更多信息。Canvas 代码示例讨论:

<!DOCTYPE html>
<html>
  
  
<head>
    
<script type="text/javascript">
    
      
//Global variables
      var myImage
= new Image(); // Create a new blank image.
      
      
// Load the image and display it.
      
function displayImage() {

        
// Get the canvas element.
        canvas
= document.getElementById("myCanvas");

        
// Make sure you got it.
        
if (canvas.getContext) {

          
// Specify 2d canvas type.
          ctx
= canvas.getContext("2d");

          
// When the image is loaded, draw it.
          myImage.onload
= function() {

            
// Load the image into the context.
            ctx.drawImage(myImage,
0, 0);

            
// Get and modify the image data.
            changeImage();
          }

          
// Define the source of the image.
          myImage.src
= "http://samples.msdn.microsoft.com/workshop/samples/canvas/kestral.png";
        }
      }

      
function changeImage() {

        ctx.strokeStyle
= "white";
        ctx.lineWidth
= "100";
        ctx.beginPath();
        ctx.arc(
100, 100, 150, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.stroke();
      }
    
</script>
  
</head>
  
  
<body onload="displayImage()">
    
<h1>
      American Kestral
    
</h1>
    
<p>
      The original image
is on the left and the modified image is on the right.
    
</p>
    
<img id="myPhoto" src="http://samples.msdn.microsoft.com/workshop/samples/canvas/kestral.png">
    
<canvas id="myCanvas" width="200" height="200">
    
</canvas>
    
<p>
      
Public domain image courtesy of U.S. Fish and Wildlife Service.
    
</p>
  
</body>

</html>


0
相关文章