在canvas上面绘制图片--drawImage实例
在canvas上面绘制图片--drawImage实例
关键点:
1、图片居中
2、其它
1 <!DOCTYPE html> 2 <html lang="zh-cn"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>8-17 课堂演示</title> 6 </head> 7 <style type="text/css"> 8 </style> 9 <body> 10 <canvas id="canvas" width="500" height="300" style="background: #A9A9A9"> 11 很抱歉,您的浏览器暂不支持HTML5的canvas 12 </canvas> 13 <input id="inps" type="range" value="1"> 14 <script> 15 16 var c=document.getElementById("canvas"); 17 var ctx=c.getContext("2d"); 18 var scaler=document.getElementById('inps') 19 var scale=0.5; 20 var img=new Image(); 21 img.src='../img/p3.jpg' 22 function draw(){ 23 var w=c.width; 24 h=c.height; 25 sw=w*scale; 26 sh=h*scale; 27 ctx.clearRect(0,0,canvas.width,canvas.height) 28 ctx.drawImage(img,-sw/2+w/2,-sh/2+h/2,sw,sh) 29 } 30 img.onload=function(){ 31 draw() 32 } 33 scaler.onchange=function(e){ 34 scale=e.target.value/50 35 alert(scale) 36 draw() 37 38 } 39 </script> 40 </body> 41 </html>