在Web应用程序中使用Canvas API

更多HTML 5文章请查阅HTML 6在线网站http://www.html5online.com.cn

本文概述

    本文介绍如何在一个Web应用程序中利用HTML 5中的Canvas API创建、编辑、打开与输出图像。

检测浏览器是否支持Canvas API
    首先,我们需要检测用户浏览器是否对HTML 5中的Canvas API提供支持。一个简单的方法是利用Modernizr工具来进行检测,方法如下所示。
if (Modernizr.canvas) {
    //浏览器支持Canvas API

else {
    //浏览器不支持Canvas API,使用诸如Flash、静态图片等其他技术
}
    通过URL地址或Data URI指定canvas元素中的图像来源
    在使用Canvas API的时候,我们首先需要在页面上放置一个canvas元素。然后,我们可以在JavaScript脚本代码中将一幅图像绘制在该canvas元素中,代码如下所示。
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.src = "images/sl.jpg";
img.onload = function () {
    ctx.drawImage(img,0,0);
}
    在这段代码中,我们首先获取页面上canvas元素的图形上下文对象,通过该对象来使用Canvas API中所定义的所有可用于绘图的方法。接下来,我们创建一个Image对象并且将该对象的src属性值定义为canvas元素中所需要绘制图像的URL地址,这将使得所需要绘制的图像将被装载在该Image对象中。当该图像装载完毕后,我们使用canvas元素的图形上下文对象的drawImage方法将该图像绘制在canvas元素中。
    可以将该Image对象的src属性值指定为一个形式为dataURI地址,代码如下所示:
  img.src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wAARCACLAGsDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGR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bsr2vbf2dl0YfbmeXCHt8SfWv8AwTo+EsmpavceNLq0/dJ+4tnr9OJoUtrOG0g/gryX9k74XWnw9+GOj2MEaJKlsm9/79aXifx5rNtqUsdj5KIj/JCkO+vh6kJ153Pdq4j2fuEuva3daDFcSXU++3nfYkyffhr5n8V/GHStL8RX+n/bkXyJimPOTivePH+sSJpMuo/uXl+58j/cfZX5+fELQZbrxrrFxbInlSXLMvyb+MDvv5rm5IHXTPr74heG9N03S08QPpXyXT/6Bb7/ALiJ/wAttlfCnxLubu81e9nnnR3d3T5P4K+7/wBqW7uYJktoZmSK2WdIkHRF9BX5++M5JJ7x3mYs3qa7IFQl7h337IXjD+xPHj6U+/ZPX6oPqsc3hLz0fY6Q/fr8c/gZLJF8SbTy2K/P2r9ULO6uR8O5f3zf8eb9/wDYoX8Qwmflx+35eO/xIS13/ceffs/v18t2E95bXS3do7wzQOjpLE+x0dP7lfT/AO35/wAlTt27vDOSfX56+ZNP+7/wOvSRxzPS9Sv31vS7LxMkCQvPM8N/EnyIl0nz7/8AYR0+f/f313v7KOvT2Hx90f8Asp3me6vPsqf7e+vMtB/5FnVU7fbLU4/7/V69/wAE+rS2vv2jPDX2yFZdt3O43DOG2da2qkR2Pav27PiLBoOpeK9KsbGG21ia/fSft0Lvvm3/AOu/3HREdP8AgdfIn7Pejx+IfjN4P0qSDzkutYtU8n/Y317R/wAFE7u5f4rzRNMxSbUdRncdmf8Acru+u3ivNv2NlVv2lvh0hGR/b0HH/fdbZjJzlyv+UxwZ+7lmljonh+0RPk8iH+CvL/FVg9h5uo6NPbJ8++HzbbfNC/8AsV6P4gRW01Nwz9yuS1u0toYkeKFVOzOQK+bUuQ7HH2255V4qfTk0j+zXvnd9ju7y/Jvd0++9fKviXVYbfXb2FdNhYJKQDt68V9Wa9bwTaTdmWJX3cnI618Z+Jbqb+27nlP4P4F/uD2qD0qEfdP/Z"
    你也许会问:"为什么需要使用dataURI地址?",这是因为dataURI地址有一些自身的优势,例如接下来我们马上要介绍的如何将canvas元素中的图形或图像导出为一个data URI地址。
    将canvas元素中的图像导出为dataURI地址
    canvas元素有一个toDataURL方法,该方法将导出图像的MIME类型作为唯一参数,代码如下所示。
window.open(document.getElementById('canvas').toDataURL("image/jpeg"));
    上面这行代码将canvas元素中的图像导出为一个JPEG格式的图像并且在新的浏览器窗口中打开该图像。浏览器地址栏中显示由canvas元素中的图像生成的data URI地址,浏览器将根据该data URI地址渲染窗口中的图像。但是,对于用户来说就好像在新的浏览器窗口中打开了该图像。
    另外请注意上面这行代码必须被运行在一个Web服务器中。从本地文件系统中直接运行该代码时浏览器将抛出错误。
将canvas元素中的图像存储在客户端本地
    通过HTML 5中提供的各种将数据存储在客户端本地的技术,我们可以很轻松地将canvas元素中的图像存储在客户端本地。
    例如通过如下所示的代码,我们可以将canvas元素中的图像存储在WebStorage中。
localStorage.setItem('canvas', canvas.toDataURL("image/jpeg"));
    通过如下所示的代码,我们可以从WebStorage中取出被保存的图像。
localStorageImage = new Image();
canvas=document.getElementById('canvas');
ctx=canvas.getContext('2d');
localStorageImage.onload = function () 
{
    ctx.drawImage(image,0,0); 
}   
localStorageImage.src = localStorage.getItem('canvas');
    将canvas元素中的图像上传到服务器端
    有时,你可能想将canvas元素中的图像上传到服务器端。这时,我们可以首先利用canvas元素的toDataURL方法将canvas元素中的图像输出为一个data URI地址,然后将该地址上传到服务器端。该地址分为两部分,中间用逗号分割,其中第一部分为“data:”+导出图像的MIME类型+“;base64”,第二部分为一个经过base64编码的字符串,在服务器端将其解码后即得到该图像的原始二进制数据,可以将其保存为图像文件,代码如下所示:
var data=canvas.toDataURL("image/jpeg");
var xhr = new XMLHttpRequest();
xhr.open("POST", "uploadImage.php");
xhr.send(data);
    服务器端保存图像文件的代码如下所示:

$data= $GLOBALS['HTTP_RAW_POST_DATA'];
$contents_split = explode(',',$data);
$encoded = $contents_split[count($contents_split)-1];
$decoded = "";
for ($i=0; $i < ceil(strlen($encoded)/256); $i++) {
    $decoded = $decoded . base64_decode(substr($encoded,$i*256,256));
}
$file=fopen("test.jpg","w");
fwrite($file,$decoded);
fclose($file);
?>

你可能感兴趣的:(HTML,5)