织梦CMS - 轻松建站从此开始!

澳奇眼镜道具厂_丹阳国际眼镜城平台

当前位置: 主页 > 网页基础 >

将任意图像转成 HTML5 Canvas

时间:2021-07-08 07:21来源: 作者: 点击:
在开始讲解技术细节之前请先看这个演示程序,输入任意的图像URL,然后点击 Img2Canvas 按钮 BTW: 同样接受 data-uri 格式数据。 代码: 01 function draw() { 02 // Get the canvas element and set the dimen
在开始讲解技术细节之前请先看这个演示程序,输入任意的图像URL,然后点击 Img2Canvas 按钮
BTW: 同样接受 data-uri 格式数据。

代码:
01 function draw() {
 
02         // Get the canvas element and set the dimensions.
 
03         var canvas = document.getElementById('canvas');
 
04         canvas.height = window.innerHeight;
 
05         canvas.width = window.innerWidth;
 
06   
 
07        // Get a 2D context.
 
08         var ctx = canvas.getContext('2d');
 
09   
 
10         // create new image object to use as pattern
 
11         var img = new Image();
 
12         img.src = document.getElementById('url').value;
 
13         img.onload = function(){
 
14             // Create pattern and don't repeat!
 
15            var ptrn = ctx.createPattern(img,'no-repeat');
 
16            ctx.fillStyle = ptrn;
 
17            ctx.fillRect(0,0,canvas.width,canvas.height);
 
18   
 
19         }
 
20  }
 
应用逻辑:
关键的地方在于 createPattern()
nsIDOMCanvasPattern createPattern(in nsIDOMHTMLElement image, in DOMString repetition);
context.createPattern(image,"repeat|repeat-x|repeat-y|no-repeat");
01 var img = new Image,
 
02    canvas = document.createElement("canvas"),
 
03    ctx = canvas.getContext("2d"),
 
04    src = "http://example.com/image"; // insert image url here
 
05  
 
06   img.crossOrigin = "Anonymous";
 
07  
 
08    img.onload = function() {
 
09      canvas.width = img.width;
 
10      canvas.height = img.height;
 
11      ctx.drawImage( img, 0, 0 );
 
12     localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") );
 
13   }
 
14  
 
15   img.src = src;
 
16   // make sure the load event fires for cached images too
 
17   if ( img.complete || img.complete === undefined ) {
 
18      img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
 
19      img.src = src;
 
20  }
  英文原文http://www.h3manth.com/content/convert-any-image-html5-canvas,OSCHINA原创翻译

(责任编辑:admin)
织梦二维码生成器
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
推荐内容