canvas--離屏效果(新增水印)
阿新 • • 發佈:2019-01-27
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>離屏canvas</title> <style> body{ background: #000;} </style> </head> <body> <!--離屏canvas:將第二個canvas加到第一個canvas中--> <div class=""> <canvas id="canvas" width="1024" height="768" style="background: #fff; border: 1px solid #aaa; display: block; margin:100px auto 0"></canvas> <!--html滑桿標籤range--> <input type="range" id="scale-range" style="display: block; margin: 20px auto; width: 800px;" min="0.5" max="3.0" step="0.01" value="1"> </div> <!--水印--> <p>水印</p> <canvas id="watermark-canvas" style=" display: block; margin: 0 auto; border: 1px solid #aaa;"></canvas> <script> var canvas=document.getElementById('canvas'); var context=canvas.getContext("2d") var slider=document.getElementById("scale-range") var watermarkcanvas=document.getElementById("watermark-canvas") var watermarkcontext=watermarkcanvas.getContext("2d") var image=new Image() window.onload=function(){ canvas.width=768; canvas.height=768; var scale=slider.value; image.src="timg.jpg"; image.onload=function(){ drawImageByScale(scale) slider.onmousemove=function(){ scale=slider.value; drawImageByScale(scale) } } } //setup watermark canvas watermarkcanvas.width=600 watermarkcanvas.height=100 watermarkcontext.font="bold 50px Arial" watermarkcontext.fillStyle="rgba(255,255,255,0.5)" watermarkcontext.textBaseline="middle"; watermarkcontext.fillText("liuyingshuiyin",20,50) function drawImageByScale(scale){ context.clearRect(0,0,canvas.width,canvas.height); //清空畫布 var imageWidth=768*scale; var imageHeight=768*scale ; var dx=canvas.width/2-imageWidth/2 var dy=canvas.height/2-imageHeight/2 context.drawImage(image,dx,dy,imageWidth,imageHeight); context.drawImage(watermarkcanvas,canvas.width-watermarkcanvas.width,canvas.height-watermarkcanvas.height); } </script> </body> </html>