欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

html5中往矩形中贴图片

程序员文章站 2023-10-27 09:28:04
分两步: 1. 画布大小就是矩形的大小 [html]       <...

分两步:

1. 画布大小就是矩形的大小
[html] 
<body onload="drawrect();"> 
   <canvas id="canvas" width="100" height="500"> 
    aaa 
    </canvas> 
</body> 

 

2. 画到矩形上的代码
[html]  www.2cto.com
<script> 
   var img_src = "./1.jpg"; 
    function drawrect() { 
       var canvas = document.getelementbyid("canvas"); 
       var context = canvas.getcontext("2d"); 
       //context.strokerect(50, 50, 120, 120); 
 
       var img=new image(); 
        //图像被装入后触发 
        img.onload=function(){ 
        context.drawimage(img,0,0); 
        } 
        img.src=img_src; 
    } 
</script> 

全部代码:
[html] 
<!doctype html> 
<html> 
<head> 
<title>html5 canvas sample</title> 
 
 <script> 
    var img_src = "./1.jpg"; 
     function drawrect() { 
        var canvas = document.getelementbyid("canvas"); 
        var context = canvas.getcontext("2d"); 
        //context.strokerect(50, 50, 120, 120); 
 
        var img=new image(); 
         //图像被装入后触发 
         img.onload=function(){ 
         context.drawimage(img,0,0); 
         } 
         img.src=img_src; 
     } 
 </script> 
</head> 
 
<body onload="drawrect();"> 
   <canvas id="canvas" width="100" height="500"> 
    aaa 
    </canvas> 
   <canvas id="canvas1" width="500" height="500"> 
    bbb 
    </canvas> 
 
</body> 
 
</html> 


作者:xiaocaiju